JavaScript upTime函数 - 无法识别变量的ID

时间:2016-07-06 01:02:12

标签: javascript

我的目标是让calcyear(cyear)最初从价值" 8"开始。每当日数达到364,我想要的价值为" 1"从这8个值中减去,直到它达到零。

出于某种原因,p id似乎没有识别出calcyear id ......或者它可能是,但代码是错误的?

整个代码:

<html>
<style>
#countup p {
display: inline-block;
padding: 0px;
margin: 0 0 10px;
}
#paragraph2 p {
display: inline-block;
padding: 0px;
margin: 0 0 10px;
}
</style>
<div id="countup">
  We are in day
  <p id="days">00</p>
  <p class="timeRefDays">of the calendar. This day has been going on for </p>
  <p id="hours">00</p>
  <p class="timeRefHours">hours, </p>
  <p id="minutes">00</p>
  <p class="timeRefMinutes">minutes, and </p>
  <p id="seconds">00</p>
  <p class="timeRefSeconds"> seconds.</p>
</div>

<div id="paragraph2">
<p>We are in month</p>
<p id="months">00</p>
<p>of the year.</p>
</div>

<div id="paragraph2">
<p>In </p>
<p id="calcyear">0</p>
<p> years an intercalation week will be added.</p>
</div>

<script>
window.onload=function() {
  upTime('mar,20,2016,00:00:00'); 
}
function upTime(countTo) {
  now = new Date();
  countTo = new Date(countTo);
  difference = (now-countTo);

  days=Math.floor(difference/(60*60*1000*24)*1);
  hours=Math.floor((difference%(60*60*1000*24))/(60*60*1000)*1);
  mins=Math.floor(((difference%(60*60*1000*24))%(60*60*1000))/(60*1000)*1);
  secs=Math.floor((((difference%(60*60*1000*24))%(60*60*1000))%(60*1000))/1000*1);
  mons=Math.floor(difference/(24*60*60*1000*24)*1);

  cyear= 8
  years=Math.floor(days / 364)
  if (years > 1){ cyear = cyear - 1}

  document.getElementById('days').firstChild.nodeValue = days;
  document.getElementById('hours').firstChild.nodeValue = hours;
  document.getElementById('minutes').firstChild.nodeValue = mins;
  document.getElementById('seconds').firstChild.nodeValue = secs;
  document.getElementById('months').firstChild.nodeValue = mons;
  document.getElementById('years').firstChild.nodeValue = years;
  document.getElementById('calcyear').firstChild.nodeValue = cyear;


  clearTimeout(upTime.to);
  upTime.to=setTimeout(function(){ upTime(countTo); },1000);
}
</script>
</html>

2 个答案:

答案 0 :(得分:0)

没有标识为years的元素,因此您的代码就会停在那里。

只需将<p id="years">0</p>添加到您的代码中即可运行。

答案 1 :(得分:0)

问题在于这部分代码:

document.getElementById('years').firstChild.nodeValue = years;

在您的HTML中,没有标识为'years'的元素,因此您将收到错误:

  

未捕获的TypeError:无法读取属性&#39; firstChild&#39;为null

由于没有ID为'years'的元素,因此document.getElementById('years')会返回null。此错误也会停止执行,因此下一行不会运行。因为它之后calcyear没有更新。

document.getElementById('years').firstChild.nodeValue = years; // Stops
document.getElementById('calcyear').firstChild.nodeValue = cyear; // Not ran

您似乎打算添加它但可能会忘记:

<div id="paragraph2">
<p>We are in month</p>
<p id="months">00</p>
<p>of the year </p>
<p id="years">00</p>  <!-- Added line -->
</div>

Demo