gpt4 book ai didi

javascript - 为什么这个 "invalid calling object"错误?

转载 作者:可可西里 更新时间:2023-11-01 01:25:35 25 4
gpt4 key购买 nike

我编写了以下 JS 并在 IE 10 中运行:

function test() {
var nodes = document.getElementsByTagName("h1");
document.writeln(nodes.length);
for (var j = 0; j < nodes.length; j++) { <=== THIS LINE!
document.writeln(j.toString());
}
document.writeln("abc");
}

但我一直收到标记行的“无效调用对象”错误。

为什么?

这是我的页面源:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" >
<head>
<title>This is JS fun!</title>
<script type="text/javascript" language="javascript" src="test.js">
</script>
</head>
<body>
<h1>1111</h1>
<h1>2222</h1>
<h1>3333</h1>
<h1>4444</h1>
<input type="button" onclick="test()" value="click me!" />
</body>
</html>

下面是我的截图:

enter image description here

最佳答案

错误出现是因为您在页面完成后运行代码。

第一个 document.writeln 调用创建了一个新文档,其中只有字符串。这意味着 nodes 中的集合不再有效。它是文档中不再存在的元素集合,因此您不能再使用该集合的任何属性(如 length)。

如果您在创建页面时运行代码,它可以正常工作:http://jsfiddle.net/Guffa/4w949/

关于javascript - 为什么这个 "invalid calling object"错误?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12990093/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com