Jquery的prop和attr

借鑑文章:html

http://www.w3help.org/zh-cn/causes/SD9006 linux

http://stylechen.com/attribute-property.html dom

http://openwares.net/linux/dom_property_element_attribute.htmlthis

一、prop和attr共性(腳踏兩隻船)spa

只要是DOM標籤中出現的屬性(html代碼),都是Attribute。而後有些經常使用特性(id、class、title等),會被轉化爲Property。能夠很形象的說,這些特性/屬性,是「腳踏兩隻船」的。.net

最後注意:「class」變成Property以後叫作「className」,由於「class」是ECMA的關鍵字。如下代碼等價:code

var className = div1.className;
var className1 = div1.getAttribute("class");


二、prop和attr的賦值和取值orm

2.一、選中prop的幾個經常使用表單屬性checked/readonly/disabled/selectedhtm

        <input id="test3" type="checkbox"/>
        var t=document.getElementById('test3');
        console.log(t.getAttribute('checked'));//null
        console.log(t.checked);//false;
        
        t.setAttribute('checked','checked');
        console.log(t.getAttribute('checked'));//checked
        console.log(t.checked);//true
        
        t.checked=false;
        console.log(t.getAttribute('checked'));//checked
        console.log(t.checked);//false

2.二、對於路徑根據本身需求,選擇賦值和取值方法
對象

        <a id="test4" href="#">Click</a>
        var t=document.getElementById('test4');
        console.log(t.getAttribute('href'));//#
        console.log(t.href);//file:///C:/Users/bsun/Desktop/ss/anonymous.html#

最後注意,setAttribute()的兩個參數,都必須是字符串。即對特性Attribute職能賦值字符串,而對屬性Property就能夠賦任何類型的值了。

2.三、style、onclick的特殊

2.3.一、用「.」style獲取

<div id="div1" class="divClass" style="width:100%; padding:10px;">100</div>
console.log(div1.style);

以上代碼中,返回了一個CSSStyleDeclaration對象,這個對象中包含着樣式的全部信息:

 2.3.2用getAttribute()獲取style

<div id="div1" class="divClass" style="width:100%; padding:10px;">100</div>console.log(div1.getAttribute("style"));

以上代碼返回的就是一個簡單的字符串:「width:100%; padding:10px;


注意:

prop和attr的使用選擇:

image

例子:

需求:當點擊全選的時候勾上全部複選框,當去掉其中一個複選框的時候,去掉全選

代碼:

     //全選    
     $('#allChkBox').click(function() {
		var bischecked = $(this).is(':checked');
		var checked = bischecked ? "checked" : "";
		$('input[name=mediaChkBox]').prop("checked", "checked");
		if (bischecked) {
			$('input[name=mediaChkBox]').prop("checked", true);
		} else {
			$('input[name=mediaChkBox]').prop("checked", false);
		}
	});
        //單選
	$('input[name=mediaChkBox]').click(function() {
		$('#allChkBox').attr('checked',false);
		var ischecked=$(this).is(':checked');
		var checkLength = $("input[name='mediaChkBox']:checked").length;
		var inputLength = $("input[name='mediaChkBox']").length;
		if(ischecked && inputLength == checkLength){
		        //若是這裏設置attr,那麼當你所有每一個選擇後,也沒法勾上全選。
			$('#allChkBox').prop('checked',true);
		}
	});
相關文章
相關標籤/搜索