jQuery removeAttr() 源码解读

removeAttr比attr的代码要简单很多~~~

    removeAttr: function( name ) {
        return this.each(function() {
            jQuery.removeAttr( this, name );
        });
    },

内部调用了jQuery.removeAttr方法,所以我们直接看它就可以啦~~

    removeAttr: function( elem, value ) {
        var name, propName,
            i = 0,
            //core_rnotwhite=/S+/g
            //value存在并且value可以匹配非空白字符
            //这一步很帅的一点就是它不动声色地把多空格分隔的字符串转为数组,所以removeAttr是可以同时移除多个属性的
            attrNames = value && value.match( core_rnotwhite );

        if ( attrNames && elem.nodeType === 1 ) {//属性节点
            while ( (name = attrNames[i++]) ) {
                //propFix 属性修正
                propName = jQuery.propFix[ name ] || name;

                // Boolean attributes get special treatment (#10870)
                //jQuery.expr.match.bool=/^(?:checked|selected|async|autofocus|autoplay|controls|defer|disabled|hidden|ismap|loop|multiple|open|readonly|required|scoped)$/i 
                if ( jQuery.expr.match.bool.test( name ) ) {
                    // Set corresponding property to false
                    elem[ propName ] = false;
                }

                elem.removeAttribute( name );
            }
        }
    }
console一下jQuery.propFix,我们发现,它原来是这样一个对象:

cellpadding-->cellPadding ...

是对大小写的修正,都转为小驼峰法

class-->className  for-->htmlFor

是考虑到js中关键字,所以将class映射到className ,js原生中就可以用element.getAttribute("className")

再看jQuery.expr.match.bool这个正则,它匹配的这些属性如checked、selected、async都是bool属性,jquery为什么要特别加一句
elem[ propName ] = false;呢?

因为对于低版本的IE(6、7)来说,单单removeAttribute并不能移除bool属性。不加这一句,我们$().attr("checked")的时候,还是会返回“checked”。

测试如下:
DEMO1
<body>
<input id="ck" type="checkbox" checked>
<script type="text/javascript">
var ck=document.getElementById('ck');
//ck.checked=false;
ck.removeAttribute('checked');
 alert(ck.getAttribute("checked"));
</scrip

DEMO2

<body>
<input id="ck" type="checkbox" checked>
<script type="text/javascript">
var ck=document.getElementById('ck');
ck.checked=false;
ck.removeAttribute('checked');
 alert(ck.getAttribute("checked"));
</script>
</body>



原文地址:https://www.cnblogs.com/qianlegeqian/p/4123893.html