簡體   English   中英

ie11 Element.children 填充

[英]ie11 Element.children polyfill

我正在做一個項目,在這個項目中我將 es6 代碼與 babel 一起使用。 我使用以下代碼:

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

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

由於沒有子屬性,它在 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 時,我可以看到原型是 Element 但沒有添加屬性。 另外在使用時:

selectorResult instanceof Element
selectorResult instanceof Node

我對兩者都是錯誤的。

目前我使用一種方法來提取孩子而不是添加到我更喜歡的原型中。

有什么建議?

提前致謝

以下代碼將屬性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 將返回一個array ,而不是一個HTMLCollection ,但你仍然可以使用Node.children.lengthNode.children[index]

使用這個 polyfill,你可以像這樣迭代你的結果:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM