Использование функций JavaScript для управления HTML - PullRequest
0 голосов
/ 05 февраля 2012

У меня возникли проблемы с работой моих функций, и моя книга, похоже, просто мусор. Я уверен, что ошибка чисто синтаксическая, хотя может быть и более.

Вот JavaScript, который я написал. Очевидно, что функция баннера не обеспечивает полную функциональность, но она должна делать что-то. В настоящее время я просто получаю ссылку на неработающее изображение.

function displayBanner(currentDate) {
    var imgSrc = defaultLogo;
    if  (currentDate.getMonth() == 1)
        imgSrc = "winterLogo";
    return ("<img src='" + imgSrc + ".gif'>");
}


function calcDaysToSale(currentDate) {
    var saleDay = new Date();
    saleDay.setDate(15);    // sets the sale date to the 15th of the current month

    // Subtracts the days remaining until the sale.
    // If the number is negative, the sale is over.
    var Days = saleDay.getDate()-currentDate.getDate();
    if (Days < 0) {
        return "The sale has ended.";
    }
    else {
        return Days;
    }
}

Теперь я думаю, что причина этого в том, что он не вызывается правильно. Вот функция, встроенная в заголовок html-страницы:

<script type="text/javascript" src="flowers.js"></script>
    <script type="text/javascript">
        function pageSetup() {
          var today = new Date(); // this creates a date object with today's date
          var banner = displayBanner(today); // *should* call the displayBanner     function

          var days = calcDaysToSale(today); // *should* call the function using today's date
          document.sale.saleMessage.value = days; // *should* set the value to days.

      // Obviously none of it works.

    }

 </script>

Я звоню pageSetup() внизу моей страницы. Я разместил полный HTML-код ниже.

Это может быть, и я почти уверен, что это чисто синтаксическая проблема. Однако то, что я подумал о Google и посмотрел в своей книге, не привело меня к каким-либо ответам.

    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Carol's Flowers</title>
<link href="flowers.css" rel="stylesheet" type="text/css" />
   <script type="text/javascript" src="flowers.js"></script>
    <script type="text/javascript">
        function pageSetup() {
          var today = new Date(); // this creates a date object with today's date
          var banner = displayBanner(today); // *should* call the displayBanner function

          var days = calcDaysToSale(today); // *should* call the function using today's date
          document.sale.saleMessage.value = days; // *should* set the value to days.

          // Obviously none of it works.

        }

     </script>

</head>

<body  class="oneColLiqCtrHdr">

<div id="container">
  <div id="header">
    <p><img name="myBanner" src="banner" id="myBanner" alt="Carol's Flowers" />
      <!-- end #header -->
    </p>
    <div id="links"><a href="#">Home</a> | <a href="#">General Arrangements</a> | <a href="#">Seasonal Designs</a> | <a href="#">Custom Orders</a> | <a href="#">Location</a></div>
  </div>
  <div id="mainContent">
    <table id="mainTable">
    <tr>
       <td width="201"><h1><img src="Flowers.JPG" alt="Random Flowers" width="200" height="255" /></h1></td>
       <td width="687">
    <p>Here at Carol's Flowers, we believe that there is a perfect floral arrangment for every occasion! Take a look around and see if there is anything you like. If we don't already have it, then we will create it for you!</p></td>
    </script>
    </tr>
    </table>
    <!-- end #mainContent --></div>
  <div id="footer">
    <p> <form name="sale" id="sale">
      Days Until Mid Month Madness Sale : 
      <input type="text" name="saleMessage" id="saleMessage" /></form></p>
    <!-- end #footer --></div>
<!-- end #container --></div>

<!-- I am trying to run the script here -->
<script type="text/javascript">
    pageSetup();
</script>

</body>
</html>

Ответы [ 4 ]

0 голосов
/ 08 июля 2013
/*Javascript potion*/




Function List:
displayBanner(currentDate)
Using the date, sets the banner image source
calcDaysToSale(currentDate)
Returns the days to sale message
*/

//display the current month from date
document.clockform.monthnow. value="99";
document.clockform.datenow. value="99";

function Banner(currentDate) 
{

var imgSrc = Banner1;
if  (currentDate.getMonth() == 2)
    imgSrc = "Banner5";

if  (currentDate.getMonth() ==7 )
    imgSrc = "Banner4";

 if  (currentDate.getMonth() == 3)
    imgSrc = "Banner3";

if  (currentDate.getMonth() == 10)
    imgSrc = "Banner2";

return ("<img  src='Banner"+bannerNum+".gif' >");
}

function calcDaysToSale(currentDate)
 {
var saleDay = new Date();
saleDay.setDate(15);   

var Days = saleDay.getDate()-currentDate.getDate();

if (Days < 0) 
{
return ("The sale has ended.");
}
else
 {
return Days;
}
}
0 голосов
/ 05 февраля 2012

Ваша функция displayBanner выглядит хорошо, но убедитесь в следующем:

  • Возвращаемая HTML-строка фактически добавлена ​​в документ правильно.Опубликуйте свой код того, как вы это делаете, если вы не уверены.
  • переменная defaultLogo определена.
  • Строка, которую вы в конечном итоге используете для источника изображения, является действительным URLкоторый идет к нужному изображению.

Вы устанавливаете переменную banner для содержания html src, возвращенного из функции displayBanner, но вы фактически ничего с этим не делаете в опубликованном вами коде,Попробуйте добавить

document.write( displayBanner(today) );

в HTML-документ, где вы хотите, чтобы изображение появилось для быстрого исправления, или поместите его где-нибудь в свой JavaScript, используя идентификатор элемента, внутри которого вы хотите, чтобы изображение появилось.

document.getElementById("desired_element_id").innerHTML = displayBanner(today);

С другой стороны, опять же, ваша функция выглядит хорошо, просто убедитесь, что вы правильно применяете ее к документу.Попробуйте добавить это к вашей функции установки страницы.

document.getElementById("saleMessage").value = days;

РЕДАКТИРОВАТЬ: Я только что проверил ваш код.Убедитесь, что вы на самом деле включаете файл 'flowers.js', поместив в него несколько предупреждений и посмотрев, появляются ли они при открытии основного документа.Кроме того, я до сих пор не могу найти нигде, где определено defaultLogo, так что это может быть причиной проблемы с изображением src.

0 голосов
/ 08 июля 2013
/*Working on same problem, did several hours of work but still need help.*/



<script type="text/javascript" src="flowers.js">
</script>

<script type="text/javascript">

var calcDaysToSale = new Date(); 
var displayBanner= getBanner(); 
var days = calcDaysToSale(); 

document.getElementById("Banner").innerHTML = displayBanner(today);
document.getElementById("saleMessage").value = days;
</script>

</head>
<body >

<div id="Banner">
<script type="text/javascript">
document.write("<img id='Banner" src='Banner"+bannerNum+".gif' alt='' />")

</script>
</div>

<div id="container">
<div id="header">
<p><img name="myBanner" src="banner" id="myBanner" alt="Carol's Flowers" />
 <!-- end #header -->
</p>
<div id="links"><a href="#">
Home
</a> 
| <a href="#">General Arrangements
</a> 
<a href="#">Seasonal Designs
</a>| 
<a href="#">Custom Orders
</a>
|<a href="#">Location
</a>
</div>
</div>
<div id="mainContent">
<table id="mainTable">
<tr>
<td width="201">
<h1>
<img src="Flowers.JPG" alt="Random Flowers" width="200" height="255" />
</h1>
</td>
<td width="687">
<p>Here at Carol's Flowers, we believe that there is a perfect floral arrangement for every occasion! Take a look around and see if there is anything you like. If we don't already have it, then we will create it for you!
</p>
</td>

</tr>
</table>
<!-- end #mainContent -->
</div>
<div id="footer">
 <p>
 <form name="sale" id="sale">

дней до середины месяца Безумия Продажа:

</body>

0 голосов
/ 05 февраля 2012

Возможно, ваша проблема в том, что URL img не найден. Проверьте в firebug, к чему разрешается URL. Возможно, вы просто не нашли правильный путь на сервере.

Показывает ли URL в firebug возвращаемое изображение? URL изображения вообще когда-либо запрашивается?

Также - вы где-то используете разметку <img>, верно? (См. Комментарий nnnnn)

Вы хотели бы сделать что-то вроде:

var banner = displayBanner(today);
document.getElementById('myPlaceholder').innerHTML = banner;

Но так как вы говорите, что видимое поврежденное изображение, проблема, вероятно, заключается в том, что URL-адрес не решается правильно.

Для локальной страницы вы можете щелкнуть правой кнопкой мыши сломанное изображение и проверить его URL.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...