我需要在脚本中使用无限循环,这样浏览器就不会卡住。我已阅读文档,我想我明白 setInterval() 函数只是每 x 毫秒执行一个函数,但此代码不起作用 - 它仅打印一次“a”。
如有任何帮助,我们将不胜感激。
<!DOCTYPE html>
<html>
<body>
<script>
setInterval(function() { document.write("a"); }, 1000);
</script>
</body>
</html>
最佳答案
加载 HTML 页面后,document.write()
语句将清除当前文档并启动一个新的空文档。新的空文档将删除文档的原始内容。
如果您想在一定时间间隔内连续向 DOM 添加某些内容,则应该使用 DOM 操作函数,而不是 document.write()
。
例如,您可以这样做:
<!DOCTYPE html>
<html>
<body>
<script>
setInterval(function() {
var span = document.createElement("span");
span.innerHTML = "a";
document.body.appendChild(span);
}, 1000);
</script>
</body>
</html>
关于javascript - document.write ("a")未附加到我的文档中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27991568/