现在的位置: 首页 > 综合 > 正文

使用jquery 1.7 及以后的版本发现的一个$.attr(“属性”)取值的一个BUG

2012年09月06日 ⁄ 综合 ⁄ 共 1542字 ⁄ 字号 评论关闭

最近打算将使用的jquery 1.4换到1.7的版本,在替换后,如下代码开始提示值是undefined

$("#ifrTest").attr("contentWindow");

于是跟进jquery的代码进行检查,发现问题出在下面的代码中:

if ( notxml ) {
            name = name.toLowerCase();
            hooks = jQuery.attrHooks[ name ] || ( rboolean.test( name ) ? boolHook : nodeHook );
        }

此处将属性名变成了全小写,导致dom对象内置的属性无法取到值。

代码所在位置第2298行,

函数attr: function( elem, name, value, pass )  中。

不知道这算不算一个BUG。如果算一个BUG,请英语好的人提交到jquery项目组去!

本人英语太差,所以悲催了!、

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

 除大小写问题外,经测试,使用getAttribute也无法直接取contentWindow的值。在1.4的版本中直接是 elem["contentWindow"]的方式返回的对象,

如果需要回避无法取值的方法,那就只有直接取DOM对象来得到该值!

测试环境 IE,FF

抱歉!评论已关闭.