简体   繁体   English

尝试更改innerHTML时出错-无法将属性'innerHTML'设置为null

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM