jquery set data attr

后端 未结 6 825
爱一瞬间的悲伤
爱一瞬间的悲伤 2020-12-14 01:35

Html

super

is #you html element change data-you attribute

相关标签:
6条回答
  • 2020-12-14 02:02

    For More Info ==> How to Get & Set Data Attribute Value From HTML Elements jQuery - Tutsmake

    Using the below syntax you can set an attribute and values.

    $(selector).attr(attribute,value);  
    

    For Set data Attribute value By Example

    $('#myClass').attr("data-id",50); 
    
    0 讨论(0)
  • 2020-12-14 02:13

    There has already been an answer chosen as a correct one, however its seems like none of the answers clearly and concisely explain what is happening.
    So let me give this a shot:

    $(element).data(key, value) does not change the html5 'data-*' attributes of the element, jQuery internally stores the key-value (in jQuery.cache).
    As a result when you call $(element).data(key) you get what is stored internally by jQuery.

    To answer your question here:

    Since you are looking to change the data-you attribute of your html tag you will instead need to use the attr() method

    Thus:

    console.log($("#you").attr("data-you")); // Hello mean
    
    $("#you").attr("data-you", "yes change you atribute");
    
    console.log($("#you").attr("data-you")); // The data-you attribute has been changed.
    
    0 讨论(0)
  • 2020-12-14 02:13
    $("#you").attr("data-you","New Value");
    
    0 讨论(0)
  • 2020-12-14 02:17

    attr() And you can not have to change the data() method.

    Try the following way:

    console.log($("#you").data("you")); // Hello mean
    
    $("#you").data("you", "yes change you atribute"); // yes change you atribute
    
    console.log($("#you").data("you")); //  yes change you atribute
    

    examples of data http://api.jquery.com/data/​​​​​​

    0 讨论(0)
  • 2020-12-14 02:24

    On your same logic, to see the result; change data to attr

    console.log($("#you").attr("data-you"));
    

    Refer LIVE DEMO

    0 讨论(0)
  • 2020-12-14 02:25

    Try this:

    $("#you").data("you", "yes change you atribute");
    
    0 讨论(0)
提交回复
热议问题