【问题标题】:JavaScript IE8: Add a function to a NodeList objectJavaScript IE8:向 NodeList 对象添加函数
【发布时间】:2014-05-17 22:11:05
【问题描述】:

我有一个对 NodeList 的引用,我只是想将一个函数附加到该对象,以便稍后由脚本的另一个区域调用。

// Quick and dirty hack to obtain a NodeList from given element(s):
var fragment = document.createDocumentFragment(),
    nodeList;
fragment.appendChild(document.getElementById("test").cloneNode(true));

nodeList = fragment.childNodes;
console.log(nodeList);

// How can a method be defined on the nodeList in IE8?
nodeList["someMethod"] = function() { alert("YOU WIN!"); };
nodeList.someMethod();

现场示例:http://jsfiddle.net/gCwAr/

以上代码适用于以下浏览器:IE9、Chrome、Firefox、Safari、Opera。

我的问题是如何让代码在 IE8 中运行,因为在倒数第二行抛出以下错误:

对象不支持该属性或方法

【问题讨论】:

    标签: javascript internet-explorer-8 cross-browser


    【解决方案1】:

    扩展宿主对象如 DOM 对象是generally a bad idea。只是不要这样做。相反,将 NodeList 包装在您自己的对象中,该对象具有您的额外方法。

    【讨论】:

    • 我使用 NodeList 而不是我自己的对象的原因是因为我想在对象上使用.defineProperty(),并且在 IE8 中(不幸的是,我必须支持),它仅适用于 DOM 对象...
    【解决方案2】:

    您可以在 IE8 中做到这一点,首先在 DOM 类原型上定义属性,例如:

    var nodeList = document.body.childNodes;
    // Define a property with the same name on the prototype object first,
    // to enable defining the property on the NodeList
    NodeList.prototype.myMethod = undefined;
    nodeList.myMethod = function () { alert("Method"); };
    nodeList.myMethod();
    

    【讨论】:

      猜你喜欢
      • 2012-11-13
      • 1970-01-01
      • 1970-01-01
      • 2019-04-20
      • 2011-11-09
      • 2010-11-06
      • 2023-03-10
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多