May 30, 2021 Article blog
In jQuery, we're going to get the properties of a label element that can be used in the attr() method or the prop() method, so what's the difference?
attr()
method sets or returns the property value of the selected element.
prop()
method sets or returns the properties and values of the selected element.
Note: By definition alone, both methods work the same way. And the usage is similar, as shown below.
Role one: Returns the property value of the selected element. The syntax is as follows:
$(selector).attr(attribute)
$(selector).prop(property)
Role 2: Set the properties and values of the selected element. The syntax is as follows:
$(selector).attr(attribute,value)
$(selector).prop(property,value)
Role 3: Set multiple properties and values. The syntax is as follows:
$(selector).attr( {attribute:value, attribute:value ...} ) //对象的写法,键值对
$(selector).prop( {property:value, property:value,...} ) //对象的写法,键值对
Role four: Use functions to set properties and values. The syntax is as follows: (usually rarely used)
//第二个参数:规定返回要设置的属性值的函数。
/*该函数包括两个参数:
* index - 检索集合中元素的 index 位置。
* oldvalue / currentvalue - 检索被选元素的当前属性值。
*/
$(selector).attr(attribute,function(index,oldvalue))
$(selector).prop(property,function(index,currentvalue))
We'll find out:
The difference between property and attribute
property
n. Property, nature, performance;
attribute
n. attribute;
Thus, the two are very confusing because the translations on the Chinese are particularly close. But in fact, they are two different things, belong to different categories.
Now, we know:
property
property. I
t is innate, not given the day after.
For example, some objects have some properties when they are defined.
attribute
attribute. I
t doesn't have it, it's given the day after.
For example, some objects customize some of the properties assigned after they are created.
Corresponding to js is:
property
is a property in the DOM, an object in JavaScript;
attribute
is an attribute (property) on an HTML label whose value can only be a string;
Corresponding to jQuery is:
$(eleStr).attr()
<img src="/smile.jpg"/>
<button>获取图像的 class 属性值</button>
12
$("button").click(function(){
console.log( $("img").attr("class") );//如果属性存在,则返回属性值;如果属性不存在,则返回 undefined
console.log( $("img").prop("class") );//如果属性存在,则返回属性值;如果属性不存在,则返回 空("")
});
$(eleStr).prop()
<input type="checkbox">
<button>获取复选框的选中状态</button>
12
$("button").click(function(){
console.log( $("input").prop("checked") ); //如果属性值存在,则返回 true;如果属性值不存在,则返回 false。
console.log( $("input").attr("checked") );//如果属性值存在,则返回 checked;如果属性值不存在,则返回 undefined。
});