jQuery的prop和attr的区别,及判断复选框是否选中
jQuery的prop和attr的区别
- 对于HTML元素本身就带有的固有属性,在处理时,使用prop方法。
- 对于HTML元素我们自己自定义的DOM属性,在处理时,使用attr方法。
参数有区别,attr()传入的是attributeName,而prop()传入的是propertyName,
Attributes vs. Properties
在这里,我们可以将attribute理解为“特性”,property理解为为“属性”从而来区分俩者的差异
例子:
<input />是否可见 <input />是否可见
//prop
$("#chk1").prop("checked") == false $("#chk2").prop("checked") == true
$("#chk2").is(":checked") == true
$('#cb').prop('checked',true);
//attr
$("#chk1").attr("checked") == undefined $("#chk2").attr("checked") == "checked"
$('#chk2').attr('checked',true);