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

柔情痞子 提交于 2019-12-05 12:39:08

问题


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').data("role") === "listview";

But this doesnt seem to add anything into the DOM?

How can I add the above data-role into the related ul tag?


回答1:


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"});



回答2:


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");



回答3:


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).



来源:https://stackoverflow.com/questions/5949741/jquery-how-to-add-html-5-data-attributes-into-the-dom

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!