本文介绍了创建一个 HTMLCollection的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试填充 Element.prototype.children
应该返回一个 HTMLCollection
不过
var h = new HTMLCollection();
//TypeErrror: HTMLCollection is not a constructor
和
var h = Object.create(HTMLCollection.prototype);
h[0] = div;
h.item(0);
// Could not convert JavaScript argument
测试 Firefox 7 和 Chrome
Test Firefox 7 and Chrome
除了填充 HTMLCollection
之外,还有什么方法可以与之交互吗?
Apart from shimming HTMLCollection
is there any way to interact with it?
如果您能提出解决方案,还请提供有关此 github 问题的反馈
Also provide feedback on this github issue if you can suggest a solution
推荐答案
我会这样做:
function MyHTMLCollection( arr ) {
for ( var i = 0; i < arr.length; i += 1 ) {
this[i] = arr[i];
}
// length is readonly
Object.defineProperty( this, 'length', {
get: function () {
return arr.length;
}
});
// a HTMLCollection is immutable
Object.freeze( this );
}
MyHTMLCollection.prototype = {
item: function ( i ) {
return this[i] != null ? this[i] : null;
},
namedItem: function ( name ) {
for ( var i = 0; i < this.length; i += 1 ) {
if ( this[i].id === name || this[i].name === name ) {
return this[i];
}
}
return null;
}
};
其中 arr
是一个常规数组,包含所有应该在 HTMLCollection 中的 DOM 元素.
where arr
is a regular array that contains all the DOM elements which should be inside the HTMLCollection.
待办事项:
- 参数
arr
应该事先检查:它是一个数组吗?该数组的所有元素都是 DOM 元素吗?
- the argument
arr
should be checked beforehand: Is it an array? Are all elements of that array DOM elements?
这篇关于创建一个 HTMLCollection的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!