jQuery removeAttr()方法 源碼解讀

來源:互聯網
上載者:User

標籤:style   blog   http   io   ar   color   sp   java   for   

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>

 



 

jQuery removeAttr()方法 源碼解讀

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.