jQuery - 如何将HTML 5数据属性添加到DOM中 [英] jQuery - How to add HTML 5 data attributes into the DOM
问题描述
我正在尝试将HTML 5数据属性添加到DOM中。我在jQuery网站上看到过数据属性的格式是:
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";
但这似乎没有在DOM中添加任何东西?
But this doesnt seem to add anything into the DOM?
如何将上述数据角色添加到相关的ul标签中?
How can I add the above data-role into the related ul tag?
推荐答案
读取这篇文章
来自文章
jQuery.com - .data( )方法
允许我们将任何类型
的数据附加到DOM元素,方式是从循环引用安全
,因此从内存泄漏
。
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."
随着HTML5的推出,我们可以将
用作属性。对于
示例
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"});
这篇关于jQuery - 如何将HTML 5数据属性添加到DOM中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!