[英]Error trying to change innerHTML — Cannot set property 'innerHTML' of null
I am trying to change the innerHTML of a div based on the number populated by a javascript function. 我试图根据由javascript函数填充的数字来更改div的innerHTML。 Unfortunately I am getting an error and I am unsure why. 不幸的是,我遇到一个错误,我不确定为什么。
Pseudocode 伪代码
If number > 2
change innerHTML to seconds
otherwise change to second
. 如果number > 2
则将innerHTML更改为seconds
否则将更改为second
。
I had a look around and I found something related to the function being triggered before the DOM. 我环顾四周,发现与DOM之前触发的功能有关的东西。 I did some changes but still no success. 我做了一些更改,但仍然没有成功。 What I am doing wrong? 我做错了什么? How can I make trigger the function after the DOM being rendered? 渲染DOM后如何使函数触发? Isn't the window.onload
already doing the work? window.onload
已开始工作?
Thank you in advance 先感谢您
JS JS
$(document).ready(function() {
window.onload = function() {
// Month,Day,Year,Hour,Minute,Second
upTime('may,05,2006,00:00:00');
};
function upTime(countTo) {
var now = new Date();
countTo = new Date(countTo);
var difference = (now - countTo);
var years = Math.floor(difference / (60 * 60 * 1000 * 24) / 365);
var days = Math.floor(difference / (60 * 60 * 1000 * 24) * 1);
var hours = Math.floor((difference % (60 * 60 * 1000 * 24)) / (60 * 60 * 1000) * 1);
var mins = Math.floor(((difference % (60 * 60 * 1000 * 24)) % (60 * 60 * 1000)) / (60 * 1000) * 1);
var secs = Math.floor((((difference % (60 * 60 * 1000 * 24)) % (60 * 60 * 1000)) % (60 * 1000)) / 1000 * 1);
document.getElementById('years').firstChild.nodeValue = years;
document.getElementById('days').firstChild.nodeValue = days;
document.getElementById('hours').firstChild.nodeValue = hours;
document.getElementById('minutes').firstChild.nodeValue = mins;
document.getElementById('seconds').firstChild.nodeValue = secs;
if (secs > 2) {
console.log('over');
document.getElementById('.seconds').innerHTML = "seconds";
} else {
console.log('lower');
document.getElementById('.seconds').innerHTML = "second";
}
clearTimeout(upTime.to);
upTime.to = setTimeout(function() {
upTime(countTo);
}, 1000);
}
});
Get element by class : document.getElementsByClassName('seconds')
and by Id document.getElementById('seconds')
按类获取元素: document.getElementsByClassName('seconds')
和ID document.getElementById('seconds')
But with jQuery, id $('#seconds')
and class $('.seconds')
但是使用jQuery, id $('#seconds')
和class $('.seconds')
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.