IE7中的Element.prototype是什么?

7

我想扩展所有dom元素,以便能够获取和删除它们的子元素。以下是函数(在FF和Chrome中有效)。在IE7中是否有相应的方法来扩展基本dom对象?

if (!Element.get) {
Element.prototype.get = function(id) {
    for (var i = 0; i < this.childNodes.length; i++) {
        if (this.childNodes[i].id == id) {
            return this.childNodes[i];
        }
        if (this.childNodes[i].childNodes.length) {
            var ret = this.childNodes[i].get(id);
            if (ret != null) {
                return ret;
            }
        }
    }
    return null;
}
}

Element.prototype.removeChildren = function() {
    removeChildren(this);
}

谢谢!


复制 https://dev59.com/w0bRa4cB1Zd3GeqP27Rf - bobince
3个回答

5

这里有一个简单的解决方法,在99%的情况下足够使用。如果需要,也可以根据您的脚本进行完善:

if ( !window.Element ) 
{
    Element = function(){};

    var __createElement = document.createElement;
    document.createElement = function(tagName)
    {
        var element = __createElement(tagName);
        if (element == null) {return null;}
        for(var key in Element.prototype)
                element[key] = Element.prototype[key];
        return element;
    }

    var __getElementById = document.getElementById;
    document.getElementById = function(id)
    {
        var element = __getElementById(id);
        if (element == null) {return null;}
        for(var key in Element.prototype)
                element[key] = Element.prototype[key];
        return element;
    }
}

我删除了我的答案并编辑了这个,之前我没有足够的声望来完成它。 - Brett Caswell

4

3

IE浏览器没有设置"Element",因此您无法访问Element的原型来直接添加函数。解决方法是重载"createElement"和"getElementById",使它们返回一个具有修改过的原型和您的函数的元素。

感谢Simon Uyttendaele提供的解决方案!

if ( !window.Element )
{
        Element = function(){}

        Element.prototype.yourFunction = function() {
                alert("yourFunction");
        }


        var __createElement = document.createElement;
        document.createElement = function(tagName)
        {
                var element = __createElement(tagName);
                for(var key in Element.prototype)
                        element[key] = Element.prototype[key];
                return element;
        }

        var __getElementById = document.getElementById
        document.getElementById = function(id)
        {
                var element = __getElementById(id);
                for(var key in Element.prototype)
                        element[key] = Element.prototype[key];
                return element;
        }
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接