Home > Web Front-end > JS Tutorial > Discussion on the issues of .attr() and .prop() in jQuery_jquery

Discussion on the issues of .attr() and .prop() in jQuery_jquery

WBOY
Release: 2016-05-16 17:23:25
Original
1106 people have browsed it

By the way, I wrote a few lines of code and it can run normally on IE8, but not on Chrome and FF. My friend said this is RP, which is depressing!

In fact, the functional requirements are as follows, two radios: male and female, and one button: reset. The startup page selects male by default. After the user selects female and clicks the reset button, it needs to be restored to the default state.

Copy code The code is as follows:





My js code is like this:
Copy code The code is as follows:

$("#reSet").click(function() {
 $("input[name='sex']:first").attr("checked",true);
});

The result is what I mentioned at the beginning. I asked several people but couldn’t explain it clearly. Later I checked the API and found out that the .prop() method was added in the jQuery1.6 version. , seems to be no different from .attr(), both can be used to get and set attribute values. Later, I learned that the .prop() method is suitable for Boolean value attributes. The official explanation is that selectedIndex, tagName, nodeName, nodeType, ownerDocument, defaultChecked, and defaultSelected properties require the .prop() method. In addition, there are many people on the Internet who say "add the attribute name and the attribute will take effect. You should use .prop()". I have not verified other attributes, but the "checked" attribute does take effect when added. Therefore, the two red points should be the difference between .attr() and .prop().

So, change the code in the click event method above to the following.
Copy code The code is as follows:

$("input[name='sex']: first").prop("checked",true);
Related labels:
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template