window.onload适用于aspx页面,但不适用于常规htm

时间:2012-09-03 23:25:17

标签: javascript asp.net javascript-events onload xhtml-1.0-strict

有人可以向我解释为什么window.onload在aspx中工作正常,但在xhtml中没有?

这个window.onload示例在aspx中工作正常:

<script type="text/javascript">
    //<![CDATA[
      //handles the collapse of submenu items on navigation side menu

 function toggle() {

     document.getElementById('node4').style.display = '';

 }

 window.onload = toggle;

//]]>
 </script>

但是这个window.onload示例在XHTML 1.0 strict中不起作用。 (当加载页面时,它不会立即触发countDownClock):

<script type="text/javascript">
   //<![CDATA[
   //handles the collapse of submenu items on navigation side menu

   function countDownClock() {
       today = new Date();
       openingDay = new Date();
       openingDay.setMonth(2, 23);
       (today > openingDay) ? openingDay.setFullYear(2013) : openingDay.setFullYear();
       openingDay.setHours(9, 0, 0, 0);
       document.getElementById("mallclock").dayNow.value = showDate(today);
       document.getElementById("mallclock").timeNow.value = showTime(today);

       var daysLeft = dayDiff(today, openingDay);
       var hoursLeft = hoursDiff(today, openingDay);
       var minutesLeft = minutesDiff(today, openingDay);

       daysLeft = ((hoursLeft - 24) >= 0) ? daysLeft + (hoursLeft / 24) : daysLeft;
       hoursLeft = ((hoursLeft - 24) >= 0) ? hoursLeft - ((hoursLeft / 24) * 24) : hoursLeft;
       hoursLeft = ((minutesLeft - 60) >= 0) ? hoursLeft + (minutesLeft / 60) : hoursLeft;
       minutesLeft = ((minutesLeft - 60) >= 0) ? minutesLeft - ((minutesLeft / 60) * 60) : minutesLeft;

       document.getElementById("mallclock").days.value = daysLeft;
       document.getElementById("mallclock").hours.value = hoursLeft;
       document.getElementById("mallclock").minutes.value = minutesLeft;

   }

   window.onload = countDownClock;

 //]]>
</script>

它只会触发body事件,该事件设置为在1分钟后显示countDownClock

   <body onload = "setInterval('countDownClock()', 60000)">

1 个答案:

答案 0 :(得分:2)

啊哈,编辑完全不同。

一个页面只能有load个事件的一个处理程序,因此如果您使用window.onload添加一个,并使用body onload属性添加另一个,则只有其中一个可以使用。

将两个动作放在同一个处理程序中:

window.onload = function(){
  countDownClock();
  window.setInterval(countDownClock, 60000);
};