Copy Code code as follows:
$ ("input"). attr ("Checked", "checked")
After setting the checkbox does not become selected, with Chrome debugging, the checkbox does have the Checked property, and the value is checked, but the page display is still unchecked
Copy Code code as follows:
$ ("input"). Prop ("checked", true);
The difference between ttributes and properties is important in certain situations. Before JQuery 1.6, the. attr () method returns the value of the property when it takes a value of some attribute, which results in inconsistency. Starting with JQuery 1.6, the. Prop () method returns the value of the property, whereas the. attr () method returns the value of attributes.
For example, SelectedIndex, TagName, NodeName, NodeType, Ownerdocument, defaultchecked, and defaultselected should use the. Prop () method to fetch or assign values. These properties are obtained using the. attr () method before jQuery1.6, but this is not the attr attribute of the element. They have no corresponding attributes (attributes), only attributes.
For example, consider the <input type= "checkbox" checked= "checked"/> defined in the HTML markup for a DOM element, and assume that it is a JavaScript variable named Elem:
elem.checked true (Boolean) changes the state of the check box
$ (elem). Prop ("checked") True (Boolean) changes the state of the check box
Elem.getattribute ("Checked") "Checked" (String) does not change the initial state of the check box;
$ (elem). attr ("Checked") (1.6) "Checked" (String) the initial state of the check box that does not change;
$ (elem). attr ("Checked") (1.6.1+) "Checked" (String) changes the state of the check box
$ (elem). attr ("Checked") (pre-1.6) True (Boolean) changes the state of the check box
According to the form specification of the checked, the property is a Boolean property, which means that as long as the attribute exists, even if it has no value, or an empty string, the property of the attribute is true. The following recommendations are compatible browsers to determine whether the checked property of a CheckBox element is "true":
Copy Code code as follows:
if (elem.checked)
if ($ (elem). Prop ("checked"))
if ($ (elem). Is (": Checked"))
If you use jquery 1.6, code if (elem). attr ("Checked"), you will get an attribute that does not change the check box is selected and selected. It is simply used to store the initial value of the default or selected property. To maintain backward compatibility, the. attr () method starts with the JQuery 1.6.1+ and, in addition to returning property values, the property properties are updated, so the Boolean attribute (Boolean property) does not need to pass. Prop () to change its value. It is recommended to use one of the above methods to obtain the checked value.