为什么此“无效的调用对象"被删除?错误? [英] Why is this "invalid calling object" error?

查看:67
本文介绍了为什么此“无效的调用对象"被删除?错误?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I write the following JS and run in 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");
}

但是对于标记的行,我一直收到无效的调用对象"错误.

But I kept get "invalid calling object" error for the marked line.

为什么?

这是我的页面来源:

<!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>

下面是我的屏幕截图:

推荐答案

出现此错误是因为页面完成后正在运行代码.

The error comes because you are running the code after the page is completed.

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

The first document.writeln call creates a new document with only the string in it. That means that the collection in nodes is no longer valid. It is a collection of elements in a document that doesn't exist any more, so you can't use any of the properties (like length) of the collection any more.

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

If you run the code while the page is being created, it works fine: http://jsfiddle.net/Guffa/4w949/

这篇关于为什么此“无效的调用对象"被删除?错误?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆