Use of prop() method in JQuery

In previous versions of JQuery, attr() was used to access the attributes of an object. For example, to take the alt attribute of an image, you can do this $("#img").attr("alt"); but in some Sometimes, such as when accessing the disabled attribute of input, there will be some problems. In some browsers, just write the disabled attribute, and in some browsers, write: disabled = "disabled". So, starting from version 1.6, JQuery provides a new method prop() to get these properties. When using prop(), the return value is the standard property: true/false, such as: $("#checkbox").prop("disabled"), it will not return "disabled" or "", only true/false . Of course, the same is true when assigning values. In this way, all operations are unified, both in terms of syntax and semantics.

So, which properties should be accessed with attr() and which should be accessed with prop()?

The first principle: only add the name of the property, the property will take effect, prop() should be used;

The second principle: only true/false attributes should use prop();

According to the official instructions, if you set disabled and checked attributes, you should use the prop() method instead of the attr() method.

The above copy: excerpted from the book "Sharp jQuery (2nd Edition)".

 [Example] JQuery realizes the check box selection all and unselect all functions, using the prop() method to set the property value.

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>JQuery中的prop()方法的使用</title>
    <meta name="author" content="pan_junbiao的博客">
</head>
<body>
    <h3>请选择用户信息:</h3>
    <input type="checkbox" name="checkItem" value="1"/> pan_junbiao的博客_01<br>
    <input type="checkbox" name="checkItem" value="2"/> pan_junbiao的博客_02<br>
    <input type="checkbox" name="checkItem" value="3"/> pan_junbiao的博客_03<br>
    <input type="checkbox" name="checkItem" value="4"/> pan_junbiao的博客_04<br>
    <input type="checkbox" name="checkItem" value="5"/> pan_junbiao的博客_05<p>
    <input type="button" value="全选" id="checkAll"/>
    <input type="button" value="全不选" id="noCheckAll"/>
</body>
<script src="/js/jquery-3.4.1.min.js"></script>
<script>
    $(document).ready(function(){
        //全选
        $("#checkAll").click(function(){
            $("[name=checkItem]:checkbox").prop("checked",true);
        });

        //全不选
        $("#noCheckAll").click(function(){
            $("[name=checkItem]:checkbox").prop("checked",false);
        });
    });
</script>
</html>

Results of the:

As can be seen from the example, the prop() method is used to set the attribute value of the check box instead of the attr() method, because if the attr() method is used, there will be browser compatibility issues.

 

Guess you like

Origin blog.csdn.net/pan_junbiao/article/details/107668785