我试图用setinterval()显示一个随机div

时间:2015-06-04 22:07:22

标签: javascript

我得到了 - 未捕获的TypeError:无法读取属性' style'为null 当我尝试运行以下内容时:

   <script type="text/javascript">
    function startRotation() {
        setInterval(resetAllDivs(), 20000);
    }
    function resetAllDivs(){
        var i;
        for(i=1; i<=15; i++) {
            document.getElementById("img"+i).style.display = "none";
        }

        displayRandom();
    }

    function displayRandom(){
        var n=Math.round(Math.random()*3)
        document.getElementById("img"+n).style.display = "block";
        document.getElementById("img"+n).style.width = "64%";
    }
</script>

我在结束时使用:

调用startRotation()
 document.addEventListener('DOMContentLoaded',function(){startRotation()});

错误指向该行:

 document.getElementById("img"+i).style.display = "none";

有什么想法吗?

2 个答案:

答案 0 :(得分:2)

有几点需要注意,其中一些已在评论中指出,但我会重申。

https://www.googleapis.com/auth/analytics.readonly 期望将函数引用作为其第一个参数,您将setInterval的调用的返回结果传递给resetAllDivs()。真的,你有

undefined

不会起作用。你想要

setInterval(undefined, 20000);

接下来,这行会给你一个0到3之间的随机数字,我不认为这是你所追求的。这就是为什么有时候你会尝试setInterval(resetAllDivs, 20000); ,这会返回document.getElementById('img0')

null

相反,这会得到1到15之间的数字:

 Math.round(Math.random()*3)

这是一个工作示例。时间减少到半秒而不是20秒。

DEMO

&#13;
&#13;
Math.floor((Math.random() * 15) + 1);
&#13;
function startRotation() {
  resetAllDivs();
  setInterval(resetAllDivs, 500);
}

function resetAllDivs(){
  for (var i = 1; i <= 15; i++) {
    document.getElementById("img" + i).style.display = "none";
  }

  displayRandom();
}

function displayRandom(){
  var n = Math.floor((Math.random() * 15) + 1);
  document.getElementById("img" + n).style.display = "block";
  document.getElementById("img" + n).style.width = "64%";
}

startRotation();
&#13;
div {
  width: 50px;
  height: 50px;
  
  background-color: red;
}

div:nth-child(even) {
  background-color: blue;
}
&#13;
&#13;
&#13;

这段代码绝对可以重构为更聪明的东西。我还建议您使用setTimeout而不是setInterval,因为您可以获得更多控制权。

答案 1 :(得分:0)

您的document.getElementById("img"+i)之一返回一个空值,这意味着在您的resetAllDvis()函数运行之前,该元素不存在或未创建。

您应该使用:

Math.floor((Math.random() * 15) + 1);

返回1到15之间的随机数。

确保您的图片的ID为id="img1"id="img15"

相关问题