【问题标题】:IE only JavaScript error Object.prototype and getElementsByTagNameIE 仅 JavaScript 错误 Object.prototype 和 getElementsByTagName
【发布时间】:2011-10-14 21:28:10
【问题描述】:
<script type="text/javascript">
Object.prototype.size = function(){
    return this.length;
};

window.onload = function(){     
    var links = document.getElementsByTagName("A");

    alert(links.size());
};
</script>

<a href="#">test1</a>
<a href="#">test2</a>
<a href="#">test3</a>
<a href="#">test4</a>

它适用于 Firefox、Chrome 和 Opera。但在 IE 中它不起作用。为什么?

任何帮助将不胜感激。

【问题讨论】:

标签: javascript internet-explorer dom


【解决方案1】:

在 IE8- 中,links instanceof Object 返回false。在 IE9 中,这可以正常工作。

这意味着.sizelinks 上不可用。您应该扩展 HTMLCollection,因为这就是 getElementsByTagName 在 IE8- 中返回的内容。请注意,这同样不适用于其他浏览器(IE9、Chrome 等),因为它们使用NodeList

您基本上不应该扩展主机对象,但这适用于 IE8:http://jsfiddle.net/wss6K/4/

HTMLCollection.prototype.size = function(){
    return this.length;
};

在 IE7 中,links.constructor === undefined 所以我认为你不能在那里扩展links 的原型。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-08-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-07-04
    相关资源
    最近更新 更多