Home > Article > Web Front-end > The difference between attr() and prop() in jQuery when modifying the checked attribute_jquery
When making the check box select button, a problem occurred. Use the statement $.attr('checked',true) to change the attribute of the check box to checked. It is the first in the chrome browser. It won't work after the first click is valid. IE8 has no problem.
Baidu took a long time to find out that the reason is that the attributes of HTML are divided into attributes and properties. Let’s call the latter properties for now.
The checked attribute is divided into attribute->checked, and property->true, false.
For a checkbox, if checked="checked" is not defined, the result of alert($.attr("checked")) is undefined. If defined, the result is checked. The attribute does not change as the status of the checkbox changes.
If prop($.attr("checked")) is used, the output will be false and true respectively. The property changes as it changes.
So prop() should be used when modifying the checked attribute. prop() was added after jQuery 1.6.
Charts about other similar properties on the Internet:
In addition, in versions before IE9, if the property is not deleted before the DOM element is removed, using the .prop() method to set the value of the DOM element property (except simple types: number, string, boolean) will cause a memory leak. . In order to safely set the value of the DOM object and avoid memory leaks, you can use the .data() method. I haven't encountered it yet, so I'll write it down here.