跟进jquery的代码进行检查,发现问题出在下面的代码中:
if ( notxml ) {
name = name.toLowerCase();
hooks = jQuery.attrHooks[ name ] || ( rboolean.test( name ) ? boolHook : nodeHook );
}
此处将属性名变成了全小写,导致dom对象内置的属性无法取到值。
代码所在位置第2298行,
attr函数完整代码:
attr: function( elem, name, value, pass ) {
var ret, hooks, notxml,
nType = elem.nodeType; // don't get/set attributes on text, comment and attribute nodes
if ( !elem || nType === 3 || nType === 8 || nType === 2 ) {
return;
} if ( pass && jQuery.isFunction( jQuery.fn[ name ] ) ) {
return jQuery( elem )[ name ]( value );
} // Fallback to prop when attributes are not supported
if ( typeof elem.getAttribute === "undefined" ) {
return jQuery.prop( elem, name, value );
} notxml = nType !== 1 || !jQuery.isXMLDoc( elem ); // All attributes are lowercase
// Grab necessary hook if one is defined
if ( notxml ) {
name = name.toLowerCase();
hooks = jQuery.attrHooks[ name ] || ( rboolean.test( name ) ? boolHook : nodeHook );
} if ( value !== undefined ) { if ( value === null ) {
jQuery.removeAttr( elem, name );
return; } else if ( hooks && "set" in hooks && notxml && (ret = hooks.set( elem, value, name )) !== undefined ) {
return ret; } else {
elem.setAttribute( name, "" + value );
return value;
} } else if ( hooks && "get" in hooks && notxml && (ret = hooks.get( elem, name )) !== null ) {
return ret; } else { ret = elem.getAttribute( name );//此处取属性的方法对属性名称是大小写敏感的 // Non-existent attributes return null, we normalize to undefined
return ret === null ?
undefined :
ret;
}
测试环境 IE,FF