標籤: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()方法 源碼解讀