2009-02-28 9 views
6

Sto cercando di estendere tutti gli elementi dom in modo da poter ottenere e rimuovere i loro figli. La funzione è sotto (funziona in FF e Chrome). Esiste un equivalente in IE7 per estendere l'oggetto dom base?Element.prototype in IE7?

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

Grazie!

+0

vittima http://stackoverflow.com/questions/592815/is-there-really-no-way-to-expose-the-prototype-of-a-html-element-in-ie-8/ – bobince

risposta

4

No. Ci sarà un supporto limitato in IE8, ma "fino ad allora è meglio trovare un altro posto dove appendere le proprie funzioni.

6

Ecco una soluzione semplice che sarà sufficiente nel 99% dei casi. Può così essere completato come richiesto dallo script:

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

rimosso la mia risposta e modificato questo, non avevo abbastanza rep per farlo prima –

3

IE non hanno serie "Element", quindi non è possibile accedere al prototipo di Element per aggiungere direttamente la vostra funzione. La soluzione alternativa è di sovraccaricare "createElement" e "getElementById" per far sì che restituiscano un elemento con un prototipo modificato con la propria funzione.

Grazie a Simon Uyttendaele per la soluzione!

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