document.getElementById(“”)。innerHTML =“”;不工作

时间:2015-10-11 10:19:53

标签: javascript html innerhtml

我见过类似的问题,但我找不到适合我的答案。我正在更改标题(h1)中的文本,具体取决于时间。该值不会改变。

<html>
<head>
<link href='https://fonts.googleapis.com/css?family=Lato:100' rel='stylesheet' type='text/css'>
</head>
<body>
<center>
  <img src = "image.png" width = "25%" height = "auto"/>
    <h1 id = "ce" style="font-weight: normal; font-family: 'lato', sans-serif; font-size:80px;">No Event</h1>
</center>
<iframe id="ytplayer" type="text/html" width="100%" height="500"
src="http://www.youtube.com/embed/M7lc1UVf-VE?autoplay=1&origin=http://example.com"
frameborder="0"/>
  <script>
 function headerChange(){
 var d = new Date();
 var m = d.getMinutes();
 var h = d.getHours();
 if(h == 7 && m>=45){
    document.getElementById("ce").innerHTML = "event1";
  }
  if(h == 8 && m>=00){
  document.getElementById("ce").innerHTML = "event2";
  }
  if(h == 8 && m>=15){
  document.getElementById("ce").innerHTML = "event3";
  }
  if(h == 8 && m>=45){
  document.getElementById("ce").innerHTML = "event4";
  }
  if(h == 9 && m>=00){
   document.getElementById("ce").innerHTML = "event5";
  }
  if(h == 9 && m>=15){
     document.getElementById("ce").innerHTML = "event6";
   }
   }
  headerChange();
  setTimeout(headerChange, 1000);
  </script>
</body>
  </html>

3 个答案:

答案 0 :(得分:0)

请关闭headerChange函数。我认为它错过了结束括号。 其次,您正在使用setTimeout和递归调用。我建议不要递归地调用它,你可以这样做

function headerChange(){
 var d = new Date();
 var m = d.getMinutes();
 var h = d.getHours();
 if(h == 7 && m>=45){
    document.getElementById("ce").innerHTML = "event1";
  }
  if(h == 8 && m>=00){
  document.getElementById("ce").innerHTML = "event2";
  }
  if(h == 8 && m>=15){
  document.getElementById("ce").innerHTML = "event3";
  }
  if(h == 8 && m>=45){
  document.getElementById("ce").innerHTML = "event4";
  }
  if(h == 9 && m>=00){
   document.getElementById("ce").innerHTML = "event5";
  }
  if(h == 9 && m>=15){
     document.getElementById("ce").innerHTML = "event6";
   }
}
  setTimeout(headerChange, 1000);

答案 1 :(得分:0)

<script>
var myVar = setInterval(headerChange, 1000);

function headerChange(){
 var d = new Date();
 var m = d.getMinutes();
 var h = d.getHours();
 var elem = document.getElementById("ce");

  if(h == 7 && m>=45){
     elem.innerHTML = "event1";
  }else if(h == 8 && m>=00){
     elem.innerHTML = "event2";
  }else if(h == 8 && m>=15){
     elem.innerHTML = "event3";
  }else if(h == 8 && m>=45){
     elem.innerHTML = "event4";
  }else if(h == 9 && m>=00){
     elem.innerHTML = "event5";
  }else if(h == 9 && m>=15){
     elem.innerHTML = "event6";
  }
}
</script>

答案 2 :(得分:0)

感谢您的所有答案! @racraman发现了问题。这是youtube iFrame。一旦我删除了特定的演示iFrame,我的代码就开始工作了。