我有这个js代码。它工作但我注意到我得到这样的错误。 " TypeError:document.getElementById(...)为null" 而且我注意到在firebug中计数错误的错误。所以我假设它是继续前进的for循环。你能看一下下面的代码并告诉我它有什么问题吗?
<script>
$( document ).ready(function() {
//Create object with the list of due dates
//The 'name' will correspond to the field ID to populate the results
var dueDates = {
'date1':'2017-04-17 09:55:18',
'date2':'2017-05-17 09:55:18',
'date3':'2017-06-17 09:55:18'
};
var timer = setInterval(function() {
//Instantiate variables
var dueDate, distance, days, hours, minutes, seconds, output;
//Set flag to repeat function
var repeat = false;
// Get todays date and time
var now = new Date().getTime();
//Iterate through the due dates
for (var dueDateId in dueDates) {
//Get the due date for this record
dueDate = new Date(dueDates[dueDateId]);
// Find the distance between now an the due date
distance = dueDate - now;
// Time calculations for days, hours, minutes and seconds
days = Math.floor(distance / (1000 * 60 * 60 * 24));
hours = Math.floor((distance % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));
minutes = Math.floor((distance % (1000 * 60 * 60)) / (1000 * 60));
seconds = Math.floor((distance % (1000 * 60)) / 1000);
//Determine the output and populate the corresponding field
output = "OVERDUE";
if (distance > 0)
{
output = days + "d " + hours + "h " + minutes + "m " + seconds + "s";
repeat = true; //If any record is not expired, set flag to repeat
}
document.getElementById(dueDateId).innerHTML = output;
//If flag to repeat is false, clear event
if(!repeat)
{
clearInterval(timer);
}
}
}, 1000);
});
</script>
&#13;
<div id="date1"></div>
<div id="date2"></div>
<div id="date3"></div>
&#13;
答案 0 :(得分:1)
您的第一个截止日期是未来,因此距离是正数,因此 repeat 在循环的第一次迭代中设置为true
。由于它在循环中永远不再变为false
,因此clearInterval
函数不会在任何for
循环迭代中执行。因此,1秒后将再次调用setInterval
回调,并重复相同的逻辑...