using $.data(“value”) versus $.attr(“data-value”)

╄→гoц情女王★ 提交于 2019-12-07 14:41:11

问题


When I use jQuery.data to change the value the attribute in the DOM doesn't change. But I like when the attribute in the DOM changes, its much easier to debug stuff.

So is it ok to use $().attr("data-value") to change data-attributes?

Just a little fiddle to show that mixing $().attr and $().data won't work well together:

http://jsfiddle.net/AvRJc/


回答1:


The data function manages a cache of data for an element that jQuery provides, not data-* attributes. The only interconnection between the data function and data-* attributes is that data will initialize its cache of information from data-* attributes if you request a key that matches a data-* attribute.

Using data to set data will never update a data-* attribute.

It's fine to use attr to update the attribute, you just need to be consistent: Either use the attribute (via attr) for both getting and setting, or use data for both getting and setting, as they manage different things.

Using attr means you're really updating the attribute on the element, which means you can use the values you set in selectors and such (both CSS and jQuery), but also means you are limited to getting and setting only string values.

Using data means you're only updating the data cache, not the element, which means you can't use those values in selectors and such (because they're not stored anywhere in the DOM), but means you can get and set the full range of JavaScript data types.



来源:https://stackoverflow.com/questions/18844744/using-datavalue-versus-attrdata-value

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