【问题标题】:NamedItem method with getElementByTagName in Chrome don't work?Chrome 中带有 getElementByTagName 的 NamedItem 方法不起作用?
【发布时间】:2013-03-08 14:03:02
【问题描述】:

我在 javascript 中有这段代码:

var prop="author";
var optele = theform.getElementsByTagName("input");
alert(optele[prop]);

但在 Chrome 中它返回 "undefined" 即使我确定“作者”标签存在。 相反,在 IE 和 Firefox 中运行良好。

但我注意到在 IE 和 Firefox 的 optele var 中有一个“namedItem”方法,但在 Chrome 中没有。

有人可以帮我在 Chrome 上运行类似的代码语法吗?

【问题讨论】:

  • 这是在 dom 就绪范围内吗?
  • “作者”标签存在”到底是什么意思?请向我们展示您的标记。不,返回的 NodeList 不会有 author 属性。

标签: javascript google-chrome


【解决方案1】:

这是因为 IE 和 FF 返回 HTMLCollection [MDN] 而不是 NodeList [MDN]NodeList 无法通过名称或 ID 提取元素(namedItem method [MDN] 所做的)。

解决方案是不使用此功能,而是遍历节点并比较 name 属性。或者,您可以使用document.getElementsByName [MDN]

来自 MDN getElementsByTagName documentation

注意:虽然 W3C 规范说 elementsNodeList,但此方法在 Gecko 和 Internet Explorer 中都返回 HTMLCollection。 Opera 返回一个NodeList,但实现了namedItem 方法,这使得它类似于HTMLCollection。截至 2012 年 1 月,仅在 WebKit 浏览器中返回的值是纯 NodeList。详情请见bug 14869

【讨论】:

    猜你喜欢
    • 2017-12-02
    • 1970-01-01
    • 2012-06-23
    • 2014-07-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-03-13
    • 2013-01-03
    相关资源
    最近更新 更多