2009-02-28 16 views
6

Tôi đang cố gắng mở rộng tất cả các yếu tố dom để tôi có thể lấy và xóa con của họ. Hàm dưới đây (hoạt động trong FF và Chrome). Có tương đương trong IE7 để mở rộng đối tượng dom cơ sở?Element.prototype trong 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); 
} 

Cảm ơn!

+0

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

Trả lời

4

Không. Sẽ có một số hỗ trợ giới hạn in IE8, nhưng 'đến lúc đó bạn nên tìm một nơi khác để treo các chức năng của mình.

6

Đây là giải pháp đơn giản sẽ đủ trong 99% các trường hợp. Nó có thể cũng được hoàn thành theo yêu cầu của kịch bản của bạn:

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

đã xóa câu trả lời của tôi và chỉnh sửa câu trả lời này, tôi không có đủ đại diện để làm điều đó trước đây –

3

IE không có "phần tử" thiết lập, vì vậy bạn không thể truy cập các nguyên mẫu của phần tử trực tiếp thêm chức năng của bạn. Giải pháp thay thế là quá tải "createElement" và "getElementById" để yêu cầu chúng trả về một phần tử có nguyên mẫu đã sửa đổi với hàm của bạn.

Cảm ơn Simon Uyttendaele về giải pháp!

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