jQuery - How to add HTML 5 data attributes into the DOM

后端 未结 3 1407
陌清茗
陌清茗 2021-02-19 10:02

I am trying to add a HTML 5 data attribute into the DOM. I have seen on the jQuery site the format for data attributes is:

$(\'.pane-field-related-pages ul\').da         


        
相关标签:
3条回答
  • 2021-02-19 10:23

    Read this article

    From article


    jQuery.com - "The .data() method allows us to attach data of any type to DOM elements in a way that is safe from circular references and therefore from memory leaks."

    With the introduction of HTML5, we can use it as attribute as well. For example

    <div data-role="page" data-hidden="true" data-options='{"name":"John"}'></div>
    
    
    //We can call it via:
    $("div").data("role") = "page";
    $("div").data("hidden") = true;
    $("div").data("options").name = "John";
    

    alternate way

    $("div").data("role", "page");
    $("div").data("hidden", "true");
    $("div").data("role", {name: "John"});
    
    0 讨论(0)
  • 2021-02-19 10:24

    In complement to diEcho response you have 2 data() methods in jQuery.

    The first one is detailled in @diEcho response, you apply .data() to a jQuery selection, it's a getter with one arguiment and a setter with more than one argument.

    The second method is jQuery.data(), applied directly to jQuery. It takes one more argument in first position, the DOM element (if you have a jQuery selection do a get(0) you get the DOM element).

    0 讨论(0)
  • 2021-02-19 10:38

    According to the documentation for .data() in the Jquery API, you need to do this to set it:

    $('.pane-field-related-pages ul').data("role", "listview");
    

    And this to check it:

    $('.pane-field-related-pages ul').data("role");
    
    0 讨论(0)
提交回复
热议问题