2009-02-28 1 views
6

すべてのdom要素を拡張して、子を取得して削除できるようにしようとしています。この機能は以下のとおりです(FFとChromeで動作します)。ベースDOMオブジェクトを拡張するためにIE7に相当するものはありますか?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

答えて

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

私の答えを削除し、これを編集した、私は前にそれを行うのに十分な担当者がなかった –

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