今天用了一下 Prototype 1.5,发现在 IE 下很多元素没有被扩展,脚本执行报错。仔细看发现了原因。
Prototype 用 Element.addMethods() 方法对页面所有元素进行扩展:
利用扩展 HTMLElement.prototype,就可以一次性对页面中的所有元素(不管是现有的还是将来新增的)进行扩展。这样做在 FireFox 中有效,然而在 IE 中没有 HTMLElement 的概念,所以无法做到一次性扩展。
但是对页面已有元素进行扩展还是可以的,就是这样
这仅仅是对现有元素的扩展,以后每次向页面添加元素,都必须调用一次 Element.extend() 方法。更麻烦的是,如果元素是通过 innerHTML 属性加到页面上的话,将不得不把页面的所有元素重新扩展一次。
总之,HTMLElement.prototype 在 IE 中没有可替代方案,在 IE 下用 prototype 将会很不爽。
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 ;
}
}
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);
});
}
$A(document.all).each( function (element) {
Element.extend(element);
});
}
这仅仅是对现有元素的扩展,以后每次向页面添加元素,都必须调用一次 Element.extend() 方法。更麻烦的是,如果元素是通过 innerHTML 属性加到页面上的话,将不得不把页面的所有元素重新扩展一次。
总之,HTMLElement.prototype 在 IE 中没有可替代方案,在 IE 下用 prototype 将会很不爽。