JQuery .data() 不起作用?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/25876274/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 11:11:38  来源:igfitidea点击:

JQuery .data() not working?

jquerycustom-data-attribute

提问by user1143682

Recently I was coding away, and I ran into a weird issue. I was attempting to assign a data attribute to a new element I had created (via jQuery), only to discover it wouldn't actually assign the attribute. See the link below for an example, the code is listed below:

最近我在写代码,遇到了一个奇怪的问题。我试图将数据属性分配给我创建的新元素(通过 jQuery),结果发现它实际上并没有分配该属性。示例见下面链接,代码如下:

http://jsfiddle.net/y95p100c/1/

http://jsfiddle.net/y95p100c/1/

Any idea why this is happening? I've never stumbled into this...

知道为什么会这样吗?我从来没有偶然发现这个......

var div = $("<div />")
$(div).data("foo", "bar")
console.log($(div)[0].outerHTML) // prints <div></div>

回答by T.J. Crowder

datadoesn't setdata-*attributes. It manages a data cache unrelated to data-*attributes. It initializesfrom data-*attributes if there are any present, but never writes to them. To write to an attribute, use attr.

data设置data-*属性。它管理与data-*属性无关的数据缓存。如果存在任何属性,它将从属性初始化data-*,但从不写入它们。要写入属性,请使用attr.

Example: Updated Fiddle

示例:更新的小提琴

var div = $("<div />")
$(div).attr("data-foo", "bar")
console.log($(div)[0].outerHTML)

What you're seeing is just one of the many ways this can be surprising. Another is that if your markup is <div id="elm" data-foo="bar"></div>and at some point you use $("#elm").data("foo")to get the value (and it will indeed be "bar"), then you do $("#elm").data("foo", "update"), the attribute remains data-foo="bar"but the data managed by datanow has fooequal to "update". But the rule above explains it: datanever writesto data-*attrs.

您所看到的只是令人惊讶的众多方式之一。另一个是,如果您的标记是,<div id="elm" data-foo="bar"></div>并且在某些时候您$("#elm").data("foo")用来获取值(并且确实会是"bar"),那么您这样做了$("#elm").data("foo", "update"),属性仍然存在,data-foo="bar"data现在管理的数据foo等于"update"。但上面的规则解释它:data从来没有写入data-*ATTRS。

回答by lonesomeday

jQuery imports the data-attributes when the element is loaded, but does not access it afterwards. The elements are stored in a jQuery internal structure. From the API:

jQuerydata-在元素加载时导入属性,但之后不会访问它。元素存储在 jQuery 内部结构中。从API

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

data-属性被拉到在第一时间中的数据属性被访问,然后不再访问或突变的(所有数据值然后被存储在内部的jQuery)。