The correct way to open attr and prop

prop()

prop() is a new method added in jQuery 1.6. It is officially recommended that properties with two attribute values ​​of true and false, such as checked, selected or disabled, use prop(), and others use attr().

The difference between prop() and attr()

  • The same points between the two:
    1. Obtain the attribute of the tag;
    2. Add attributes to the specified tag;
  • Differences:
    1. When obtaining the attribute value that comes with the tag, use the prop() method;
    2. When obtaining custom attributes, you can only use the attr() method;
  • When to use prop() and attr()?
    Example 1: Obtain the built-in attributes and custom attributes of the button tag
    <button goodsid="531" class="addShopping"></button>
    
    goodsidAttributes are custom attributes, when using the attr() method:
    > $('.addShopping').attr("goodsid")
    "531"
    
    And when using the prop() method:
    > $('.addShopping').prop("goodsid")
    undefined
    
    calssIt is an attribute that comes with the button tag, but when using the attr() and prop() methods to get the attribute value:
    > $('.addShopping').prop("class")
    "addShopping"
    
    > $('.addShopping').attr("class")
    "addShopping"
    
    Example 2: Get the checked, disabled, and selected attributes of the input tag :
    <!--复选框-->
    <input type="checkbox" checked id="12">
    
    <!--输入框-->
    <input type="text" disabled id="23">
    
    <!--下拉选择框-->
    <select id="34">
        <option>aaa</option>
        <option selected="">bbb</option>
    </select>
    
    search result:
    //复选框
    > $('#12').attr('checked')
    "checked"
    > $('#12').prop('checked')
    false
    
    //输入框
    > $('#23').attr('disabled')
    "disabled"
    > $('#23').prop('disabled')
    true
    
    //下拉选择框
    > $('#34').find('option').attr('selected')
    "selected"
    > $('#34').find('option').prop('selected')
    false
    
    In Example 2, attr()the query attribute value is trueand false, and the query result is inconvenient to use; but prop()the query result is trueand false.

Summarize

1. When obtaining the attributes that come with the tag, you can use prop()、attr()either ;
2. When obtaining custom attributes, it is recommended to use attr();
3. When the attribute value of the obtained attribute trueis or false, such as: when the attribute is disabled, checked, selectedit is recommended to use prop().

Guess you like

Origin blog.csdn.net/qq_42349944/article/details/100978435