Home  >  Article  >  Web Front-end  >  The difference between attr() and prop() in jQuery when modifying the checked attribute_jquery

The difference between attr() and prop() in jQuery when modifying the checked attribute_jquery

WBOY
WBOYOriginal
2016-05-16 16:41:371366browse

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.

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn