[英]'Cannot set property “innerHTML” of undefined'
I'm trying to write a pretty simple script to set an element's innerHTML to the time. 我正在尝试编写一个非常简单的脚本来将元素的innerHTML设置为时间。 However, Javascript keeps throwing a "Cannot set property 'innerHTML' of undefined" error.
但是,Javascript不断抛出“无法设置属性'innerHTML'的未定义”错误。 During debugging, I've simplified my script to the point that it runs right after element (a
<span>
) is coded, so I know it should have loaded already. 在调试过程中,我已将脚本简化为在元素(
<span>
)编码后立即运行,因此我知道它应该已经加载了。 I've also tried running this script as a <body onload=
argument - same error. 我也尝试将此脚本作为
<body onload=
参数运行 - 同样的错误。 I can't tell what I'm doing wrong. 我不知道我做错了什么。
<div style="position: fixed; right: 10px; top: 10px; width: auto; font-size: 16pt; border: 2px solid #000000;">
<span id="clock">Loading...</span>
<script type="application/x-javascript">
function setClock(spanid){
var d = new Date();
document.getElementById[spanid].innerHTML = d.getHours() + ":" + d.getMinutes() + ":" + d.getSeconds;
}
setClock("clock");
</script>
</div>
Any help is appreciated! 任何帮助表示赞赏!
You are not calling getElementById
, you are attempting to index it. 你没有调用
getElementById
,你试图索引它。 Since it is not an array and does not expose array-like behavior, the result is undefined
. 由于它不是数组并且不公开类似数组的行为,因此结果是
undefined
。 Replace your getElementById[spanId]
with getElementById(spanId)
. 用
getElementById(spanId)
替换你的getElementById[spanId]
。
[]
instead of ()
in document.getElementById(spanid)
. []
代替()
中document.getElementById(spanid)
getElementById
is function, it has to be invoked with ()
and pass the parameter inside it. getElementById
是函数,它必须用()
调用并传递其中的参数。
Also missing ()
after getSeconds()
也下落不明
()
后getSeconds()
<div style="position: fixed; right: 10px; top: 10px; width: auto; font-size: 16pt; border: 2px solid #000000;">
<span id="clock">Loading...</span>
<script type="application/x-javascript">
function setClock(spanid){
var d = new Date();
document.getElementById(spanid).innerHTML = d.getHours() + ":" + d.getMinutes() + ":" + d.getSeconds();
}
setClock("clock");
</script>
</div>
change []
to ()
: 将
[]
更改为()
:
function setClock(spanid){
var d = new Date();
document.getElementById(spanid).innerHTML = d.getHours() + ":" + d.getMinutes() + ":" + d.getSeconds;
}
And now that you have this fixxed add this: 现在你有了这个fixxed添加这个:
setInterval(function () {
function setClock(spanid) {
var d = new Date();
document.getElementById(spanid).innerHTML = d.getHours() + ":" + d.getMinutes() + ":" + d.getSeconds();
}
setClock("clock");
}, 1);
And you have an actual clock :D 你有一个实际的时钟:D
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.