2009-02-28 8 views
6

나는 모든 DOM 요소를 확장하여 자녀를 가져오고 제거 할 수 있습니다. 이 기능은 아래에 있습니다 (FF 및 Chrome에서 작동). 기본 DOM 객체를 확장하기 위해 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); 
} 

감사!

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