【发布时间】:2018-08-28 12:18:25
【问题描述】:
我正在制作一个非常简单的页面,它只计算用户打开标签的秒数。在控制台中秒更新,但在浏览器的页面上,它不是。
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8"/>
<title>Counter</title>
<script type="text/javascript">
window.seconds = document.getElementById('counts');
var count = setInterval('counter()', 1000);
function counter(){
console.log(seconds)
document.getElementById('counts').innerHTML = window.seconds + 1;
}
</script>
<style>
h2 {
text-align:center;
color:#032441;
font-family:monospace;
}
div {
text-align:center;
color:#032441;
font-size:70px;
font-family:monospace;
}
</style>
</head>
<body>
<script>
document.body.style.backgroundColor = "#EBE9BD"
</script>
<h2>
You have been on this page for
</h2>
<div id="counts">
0
</div>
<h2>
seconds.
</h2>
</body>
</html>
有什么问题?
【问题讨论】:
-
为了改变一个DOM元素的文本,你应该使用innerHTML属性。看看那个,看看你能不能解决这个问题。
-
在您提供的代码中,您没有更新
#counts的值,这不是语法错误,而是缺少代码。 -
所以我添加了 document.getElementById('counts').innerHTML = window.seconds + 1;但在浏览器上它只是转到一个然后停止,并且 colsole 每秒更新一次“null”。这是因为我没有更新变量“window.seconds”吗? (代码链接已更新)[更新,我知道了]
标签: javascript html setinterval var