Prototype, IE 的痛

本文探讨了Prototype 1.5在Internet Explorer浏览器中的兼容性问题,特别是关于Element扩展的问题。由于IE中不存在HTMLElement概念,导致无法对所有元素进行一次性扩展。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

今天用了一下 Prototype 1.5,发现在 IE 下很多元素没有被扩展,脚本执行报错。仔细看发现了原因。

Prototype 用 Element.addMethods() 方法对页面所有元素进行扩展:
Element.addMethods =  function (methods) {
  Object.extend(Element.Methods, methods || {});

  
function  copy(methods, destination, onlyIfAbsent) {
    onlyIfAbsent = onlyIfAbsent || 
false ;
    
var  cache = Element.extend.cache;
    
for  ( var  property  in  methods) {
      
var  value = methods[property];
      
if  (!onlyIfAbsent || !(property  in  destination))
        destination[property] = cache.findOrStore(value);
    }
  }

  
if  ( typeof  HTMLElement != 'undefined') {
    copy(Element.Methods, HTMLElement.prototype);
    copy(Element.Methods.Simulated, HTMLElement.prototype, 
true );
    copy(Form.Methods, HTMLFormElement.prototype);
    [HTMLInputElement, HTMLTextAreaElement, HTMLSelectElement].each(
function (klass) {
      copy(Form.Element.Methods, klass.prototype);
    });
    _nativeExtensions = 
true ;
  }
}

利用扩展 HTMLElement.prototype,就可以一次性对页面中的所有元素(不管是现有的还是将来新增的)进行扩展。这样做在 FireFox 中有效,然而在 IE 中没有 HTMLElement 的概念,所以无法做到一次性扩展。

但是对页面已有元素进行扩展还是可以的,就是这样
if  (document.all) {
    $A(document.all).each(
function (element) {
        Element.extend(element);
    });
}

这仅仅是对现有元素的扩展,以后每次向页面添加元素,都必须调用一次 Element.extend() 方法。更麻烦的是,如果元素是通过 innerHTML 属性加到页面上的话,将不得不把页面的所有元素重新扩展一次。

总之,HTMLElement.prototype 在 IE 中没有可替代方案,在 IE 下用 prototype 将会很不爽。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值