IE7中的Element.prototype?

时间:2009-02-28 01:10:09

标签: javascript dom internet-explorer-7 extend

我正在尝试扩展所有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);
}

谢谢!

3 个答案:

答案 0 :(得分:6)

这是一个简单的解决方法,在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;
    }
}

答案 1 :(得分:4)

没有。会有一些有限的支持in IE8,但是“在那之前你最好找另一个地方挂你的职能。”

答案 2 :(得分:3)

IE没有设置“元素”,因此您无法访问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;
        }
}