借鉴文章:
http://www.w3help.org/zh-cn/causes/SD9006
http://stylechen.com/attribute-property.html
http://openwares.net/linux/dom_property_element_attribute.html
1、prop和attr共性(脚踏两只船)
只要是DOM标签中出现的属性(html代码),都是Attribute。然后有些常用特性(id、class、title等),会被转化为Property。可以很形象的说,这些特性/属性,是“脚踏两只船”的。
最后注意:“class”变成Property之后叫做“className”,因为“class”是ECMA的关键字。以下代码等价:
var className = div1.className; var className1 = div1.getAttribute("class");
2、prop和attr的赋值和取值
2.1、选中prop的几个常用表单属性checked/readonly/disabled/selected
<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.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.3、style、onclick的特殊
2.3.1、用“.”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); } });