jQuery - 如何将 HTML 5 数据属性添加到 DOM
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/5949741/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
jQuery - How to add HTML 5 data attributes into the DOM
提问by Adi
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:
我正在尝试将 HTML 5 数据属性添加到 DOM 中。我在 jQuery 站点上看到数据属性的格式是:
$('.pane-field-related-pages ul').data("role") === "listview";
But this doesnt seem to add anything into the DOM?
但这似乎并没有在 DOM 中添加任何东西?
How can I add the above data-role into the related ul tag?
如何将上述数据角色添加到相关的 ul 标签中?
回答by diEcho
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
jQuery.com - “.data() 方法允许我们以一种安全的方式将任何类型的数据附加到 DOM 元素,从而避免循环引用,从而避免内存泄漏。”
随着 HTML5 的引入,我们也可以将其用作属性。例如
<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"});
回答by Karen
According to the documentation for .data() in the Jquery API, you need to do this to set it:
根据 Jquery API 中 .data() 的文档,您需要这样做来设置它:
$('.pane-field-related-pages ul').data("role", "listview");
And this to check it:
这是检查它:
$('.pane-field-related-pages ul').data("role");
回答by regilero
In complement to diEcho response you have 2 data() methods in jQuery.
作为 diEcho 响应的补充,您在 jQuery 中有 2 个 data() 方法。
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.
第一个在@diEcho 响应中有详细说明,您将.data()应用于 jQuery 选择,它是一个带有一个参数的 getter 和一个带有多个参数的 setter。
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).
第二种方法是jQuery.data(),直接应用于 jQuery。它在第一个位置还有一个参数,即 DOM 元素(如果您有一个 jQuery 选择,则执行 get(0) 您将获得 DOM 元素)。