prop()
prop() is a new method added in jQuery 1.6. It is officially recommended that properties with two attribute values of true and false, such as checked, selected or disabled, use prop(), and others use attr().
The difference between prop() and attr()
- The same points between the two:
1. Obtain the attribute of the tag;
2. Add attributes to the specified tag; - Differences:
1. When obtaining the attribute value that comes with the tag, use the prop() method;
2. When obtaining custom attributes, you can only use the attr() method; - When to use prop() and attr()?
Example 1: Obtain the built-in attributes and custom attributes of the button tag<button goodsid="531" class="addShopping">+</button>
goodsid
Attributes are custom attributes, when using the attr() method:
And when using the prop() method:> $('.addShopping').attr("goodsid") "531"
> $('.addShopping').prop("goodsid") undefined
calss
It is an attribute that comes with the button tag, but when using the attr() and prop() methods to get the attribute value:
Example 2: Get the checked, disabled, and selected attributes of the input tag :> $('.addShopping').prop("class") "addShopping" > $('.addShopping').attr("class") "addShopping"
search result:<!--复选框--> <input type="checkbox" checked id="12"> <!--输入框--> <input type="text" disabled id="23"> <!--下拉选择框--> <select id="34"> <option>aaa</option> <option selected="">bbb</option> </select>
In Example 2,//复选框 > $('#12').attr('checked') "checked" > $('#12').prop('checked') false //输入框 > $('#23').attr('disabled') "disabled" > $('#23').prop('disabled') true //下拉选择框 > $('#34').find('option').attr('selected') "selected" > $('#34').find('option').prop('selected') false
attr()
the query attribute value istrue
andfalse
, and the query result is inconvenient to use; butprop()
the query result istrue
andfalse
.
Summarize
1. When obtaining the attributes that come with the tag, you can use prop()、attr()
either ;
2. When obtaining custom attributes, it is recommended to use attr()
;
3. When the attribute value of the obtained attribute true
is or false
, such as: when the attribute is disabled
, checked
, selected
it is recommended to use prop()
.