Suppose we need a scenario like this: there is a checkbox on the page, and we expect to use Jquery to determine whether it is selected, or use Jquery to make it selected.
In versions earlier than JQ1.6, We will write our Code as follows:
Copy codeThe Code is as follows:
<Input type = 'checkbox' id = 'cb '/>
<Script>
// Obtain whether or not selected
Var isChecked = $ ('# cb'). attr ('checked ');
// Set the selected
$ ('# Cb'). attr ('checked', true );
</Script>
This is done before JQ1.6, but when we upgrade JQ1.6 to a later version, the problem arises. At this time, we will find:
$ ('# Cb'). attr ('checked'); The returned value is checked or undefined, not true or false.
In addition, the checked attribute has been initialized during page initialization and will not change as the status changes. Therefore, if the checkbox is selected at the beginning, the returned value is checked. If it is not selected at the beginning, the returned value is undefined.
The solution is:
Copy codeThe Code is as follows:
<Input type = 'checkbox' id = 'cb '/>
<Script>
// Obtain whether or not selected
Var isChecked = $ ('# cb'). prop ('checked ');
// Or
Var isChecked = $ ('# cb'). is (": checked ");
// Set the selected
$ ('# Cb'). prop ('checked', true );
</Script>
The reason is analyzed. You can understand it as follows:
It distinguishes "attributes" from "Features". attributes refer to "name, id", and so on, and features refer to "selectedIndex, tagName, nodeName.
After JQ1.6, attributes can be obtained through the attr method and features can be obtained through the prop method.
Copy codeThe Code is as follows:
$ ("# Cb"). attr ("tagName"); // undefined
$ ("# Cb"). prop ("tagName"); // INPUT