gpt4 book ai didi

javascript - ie11 Element.children 填充

转载 作者:太空宇宙 更新时间:2023-11-04 16:06:14 25 4
gpt4 key购买 nike

我正在开发一个项目,其中我将 es6 代码与 babel 结合使用。我使用以下代码:

 let result= xmlDocument.querySelector("xmlNodeSelector");

for (let child of result.children) { /* do something */ }

由于没有children属性,它在IE11上不起作用的问题。

我创建了以下polyfill,但没有帮助:

if(Element.prototype.hasOwnProperty('children')){
return;
}

Object.defineProperty(Element.prototype, 'children', {
get: function(){

let children = new HTMLCollection();

for(let i=0; i < this.childNodes.length; i++){
let item = this.childNodes[i];

if(item.nodeName !== '#text'){
children.push(item);
}
}

return children;
}
});

当我调试IE11时,我可以看到原型(prototype)是Element,但属性没有添加。另外使用时:

selectorResult instanceof Element
selectorResult instanceof Node

我对这两点都错了。

目前,我使用一种方法来提取子项,而不是添加到原型(prototype)中,这是我更喜欢的。

有什么建议吗?

提前致谢

最佳答案

以下代码将属性 children 添加到所有 HTML、XML 和 SVG 元素 - 刚刚在 IE11 下测试:

//make sure we have Node.children and Element.children available
(function (constructor) {
if (constructor &&
constructor.prototype &&
constructor.prototype.children == null) {
Object.defineProperty(constructor.prototype, 'children', {
get: function () {
var i = 0, node, nodes = this.childNodes, children = [];
//iterate all childNodes
while (node = nodes[i++]) {
//remenber those, that are Node.ELEMENT_NODE (1)
if (node.nodeType === 1) { children.push(node); }
}
return children;
}
});
}
//apply the fix to all HTMLElements (window.Element) and to SVG/XML (window.Node)
})(window.Node || window.Element);

我在 MDN 上找到了这个 polyfill。

这个polyfill将返回一个数组,而不是一个HTMLCollection,但您仍然可以使用Node.children.lengthNode.children[索引]

使用这个polyfill,你可以像这样迭代你的结果:

var resChildren = result.children
var index, maxindex;
for (index=0, maxindex=resChildren.length; index<maxindex; index++)
{
/* do_something_with(resChildren[index]); */
}

关于javascript - ie11 Element.children 填充,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41847901/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com