JQuery .data() not working?

寵の児 提交于 2019-11-26 15:51:39

问题


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:

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>

回答1:


data doesn't set data-* attributes. It manages a data cache unrelated to data-* attributes. It initializes from data-* attributes if there are any present, but never writes to them. To write to an attribute, use 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 data now has foo equal to "update". But the rule above explains it: data never writes to data-* attrs.




回答2:


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:

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



来源:https://stackoverflow.com/questions/25876274/jquery-data-not-working

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