借鉴文章: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的使用选择:
例子:
需求:当点击全选的时候勾上全部复选框,当去掉其中一个复选框的时候,去掉全选
代码:
//全选 $('#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); } });