我有一个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();
以上代码适用于以下浏览器:IE9,Chrome,Firefox,Safari,Opera。
我的问题是如何让代码在IE8中运行,因为倒数第二行会抛出以下错误:
Object不支持此属性或方法
答案 0 :(得分:1)
扩展DOM对象等主机对象为generally a bad idea。不要这样做。相反,将NodeList包装在您自己的对象中,该对象具有额外的方法。
答案 1 :(得分:0)
您可以在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();