2009-02-28 20 views
6

我試圖擴展所有DOM元素,所以我可以得到並刪除他們的孩子。該功能如下(適用於FF和Chrome)。在IE7中是否有擴展基本dom對象的等價物?IE7中的Element.prototype?

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

謝謝!

+0

欺騙http://stackoverflow.com/questions/592815/is-there-really-no-way-to-expose-the-prototype-of-a-html-element-in-ie-8/ – bobince 2009-02-28 01:53:29

回答

4

不會。會有一些有限的支持in IE8,但是'直到那時你最好找另一個地方掛你的功能。

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

刪除了我的答案並編輯了這一個,之前我沒有足夠的代表去做 – 2013-06-01 19:32:56

3

IE沒有「元素」集,所以你不能訪問元素的原型,直接添加功能。解決方法是重載「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; 
     } 
}