Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/385.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 我试图用setinterval()显示一个随机div_Javascript - Fatal编程技术网

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

Javascript 我试图用setinterval()显示一个随机div,javascript,Javascript,我正在获取-未捕获的TypeError:无法读取null的属性“style” 当我尝试运行以下操作时: <script type="text/javascript"> function startRotation() { setInterval(resetAllDivs(), 20000); } function resetAllDivs(){ var i; for(i=1; i<=15; i++)

我正在获取-未捕获的TypeError:无法读取null的属性“style” 当我尝试运行以下操作时:

   <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>
错误指向以下行:

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

有什么想法吗?

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

你应使用:

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

返回一个介于1和15之间的随机数


请确保您有id为从
id=“img1”
id=“img15”
的图像。有几件事需要注意,其中一些已经在评论中指出,但我要重申

setInterval
要求函数引用作为其第一个参数,您将调用的返回结果传递给
resetAllDivs()
,该返回结果是
未定义的
。真的吗

setInterval(undefined, 20000);
这是行不通的。你想要

setInterval(resetAllDivs, 20000);
接下来,这一行将给你一个0-3之间的随机数,我认为这不是你想要的。这就是为什么有时您会尝试
document.getElementById('img0')
,它返回
null

 Math.round(Math.random()*3)
相反,这将得到一个介于1到15之间的数字:

Math.floor((Math.random() * 15) + 1);
下面是一个工作示例。计时时间从20秒缩短到半秒

函数startRotation(){
resetAllDivs();
设置间隔(重置所有divs,500);
}
函数resetAllDivs(){

对于(var i=1;我没有15个IMG,ID为img1-15?@zfrisch,是的-除了ID在包含IMG的div上注意,你不应该自己调用函数,否则
setInterval
实际上什么都不做。在不调用函数的情况下传递函数本身。@Vohuman,你能进一步解释一下吗?你的意思是我不应该调用它吗DOMContentLoaded上的startRotation()?@RogerCreasy,因为有些人不理解向下投票的意义。非常感谢!您的代码让我克服了错误。我也非常感谢您的解释!
Math.floor((Math.random() * 15) + 1);