6

我试图打电话document.getElementsByTagName,结果我回来undefined了,不管我传递什么参数。(即使我通过“*”。)

我尝试用谷歌搜索它,但所有搜索结果都是关于未定义的 getElementsByTagName 结果数组的元素。我得到的是undefined结果本身,它把我逼到了墙角。

有谁知道这会导致什么?(使用 Firefox 12.0。在 Chrome 中我得到了预期的结果。)

编辑:好的,这是示例代码:

function buttonClick(){
   var xhr = new XMLHttpRequest();
   var msg = document.getElementById('message');
   var buttons = document.getElementsByTagName("button");
   var button, i;
   for (i = 0; i < buttons.length; ++i){
      button = buttons[i];
      msg.removeChild(button);
   }

   xhr.onreadystatechange = function() {
        if(xhr.readyState == 4){
            handleResult(xhr.responseText, msg);
        }
   };
   xhr.open("POST", location.href, true);
   xhr.setRequestHeader("Content-type","application/x-www-form-urlencoded");
   xhr.send("cmd=MyCommand");
}

并且getElementsByTagName总是返回undefined,无论我是在 Firebug 的 Script 选项卡中跟踪它还是从 Console 选项卡中调用它。(也在 Firebug 中,因为这似乎让人们感到困惑。显然有太多的控制台漂浮在周围。)。

作为证明,这是我尝试使用 Firebug 控制台时得到的结果:

>>> document.getElementsByTagName("button");
undefined
>>> msg.getElementsByTagName("button");
undefined
>>> msg.getElementsByTagName
getElementsByTagName()
>>> msg.getElementsByTagName("BUTTON");
undefined
>>> msg.getElementsByTagName("*");
undefined
>>> document.getElementsByTagName("*");
undefined
>>> document.getElementsByTagName("body");
undefined

标记是(或应该是)不相关的。这是一个有效的、格式良好的 HTML 页面,上面有一些按钮和其他元素。此 JS 函数附加到onclick其中一个按钮上。但它看起来像这样:

<html xmlns="http://www.w3.org/1999/xhtml"><head>
blah
</head>
<body>
<script type="text/javascript" src="/myJS.js"></script>
<div id="page-container">
   <div id="message"><button onclick="buttonClick();">Button 1</button><button onclick="ButtonClick2()">Button 2</button></div>

</div>

</body></html>
4

4 回答 4

8

编辑:

这是 firebug 中的错误,已通过升级到1.10.0a7 修复


因为这个方法是不可能返回undefined的,所以有两种可能:

  • 你的调试工具在骗你
  • document.getElementsByTagName没有引用原始主机对象。function getElementsByTagName() {[native code]}它应该在控制台中引用时打印 。

您应该能够可靠地查看它是否实际上是undefined(在 Firefox 中):

delete window.alert;
window.alert(buttons);

如果已经在引用原始主机对象,则它delete是一个 NOOP window.alert,否则它将恢复它。

如果它发出警报 undefined,您应该可以这样做

delete document.getElementsByTagName

恢复宿主对象引用。

这里所有的控制台引用都是指firefox默认自带的内置Web Console。

于 2012-05-27T16:59:08.390 回答
0

REPL 不是一个独立的、独立于浏览器的 JavaScript 环境吗?虽然,在您的情况下,它恰好作为插件在您的浏览器中运行,但它应该模仿一个“洁净室”,说...

总结这个人的回答:document.getElementById() 在使用 mozrepl 时返回 null (但不是在 firebug 中)

默认情况下,您在浏览器的上下文中,而不是在文档的上下文中。

试试这个来切换到文档:

repl.enter(content)
于 2012-05-27T16:49:40.387 回答
0

当我很难看到语法错误时,我遇到了问题。当我应该使用方括号时,我使用了括号

错误的:

selectedItem._element.childNodes(0).getElementsByTagName('input').item();

对:

selectedItem._element.childNodes[0].getElementsByTagName('input').item();

看到不同?请注意,顶级语法适用于旧版本的 IE,如 IE8,但它不适用于 ie10、ie11、Edge 等

于 2017-03-28T20:16:58.530 回答
0

你不能提醒Array,你应该做一个 for 循环来提醒它。例子:

var x = document.getElementsByTagName('a');
for (var i = 0, c = x.length ; i < c ; i++) {
    alert('Element n° ' + (i + 1) + ' : ' + x[i]);
}
于 2019-01-20T17:16:09.407 回答