繁体   English   中英

IE7中的Element.prototype?

[英]Element.prototype in IE7?

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

谢谢!

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

不会。 在IE8中会有一些有限的支持,但是在那之前你最好找另一个地方挂起你的功能。

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;
        }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM