0

假设我有简单的代码:

$(".myclass").data("key", "value");

我最初希望在我的 Chrome 浏览器中找到类似的东西

<div class="myclass" data-key="value">

但我没有。此外,不会应用以下 css:

[data-key='value'] { background-color: red; }

仔细想想,它不存在是有道理的,因为将它写入 html 文件是一种将数据传递给 javascript 的方式,而不是相反。

但是,出于测试目的,我想知道是否可以使用我的浏览器查看数据中存储的内容。我正在使用 Chrome,但我希望所有浏览器都应该类似。谢谢。

4

1 回答 1

2

Jquery data api doesn't add an attribute to the DOM element. It just stores the value in data cache along with other data attribute values which is present in the DOM element as a data-*. What you need to do it to add attribute.

$(".myclass").attr("data-key", "value");

The data- attributes are pulled in the first time the data property is accessed and then are no longer accessed or mutated (all data values are then stored internally in jQuery).

You can look at all the data attached to an element using

 $(".myclass").data();

It will return the object with all kvp.

于 2013-10-15T21:50:35.230 回答