使用$ .data(" value")与$ .attr(" data-value") [英] using $.data("value") versus $.attr("data-value")
问题描述
当我使用 jQuery.data
更改值时,DOM中的属性不会更改。
但我喜欢当DOM中的属性发生变化时,它更容易调试。
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.
所以可以使用 $ ()。attr(data-value)
更改数据属性?
So is it ok to use $().attr("data-value")
to change data-attributes?
只是有点小提示,表明混合 $()。attr
和 $()。data
不能很好地协同工作:
Just a little fiddle to show that mixing $().attr
and $().data
won't work well together:
推荐答案
数据
函数管理jQuery提供的元素的数据缓存,而不是 data - *
属性。 数据
函数和数据 - *
属性之间唯一的互连是数据$如果您请求与
数据匹配的密钥,c $ c>将初始化来自
属性。 data - *
属性的信息缓存 - *
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.
可以使用 attr
要更新属性,您只需要保持一致:使用属性(通过 attr
)获取和设置,或使用数据
进行获取和设置,因为他们管理不同的事情。
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.
使用 attr
意味着你真的在更新元素的属性,这意味着你可以使用你在selectors等中设置的值(CSS和jQuery),但是也意味着您只能获取和设置字符串值。
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.
使用数据
表示你只是更新数据缓存,而不是元素,这意味着你不能在选择器中使用这些值等(因为它们不存储在DOM中的任何位置),但这意味着您可以获取并设置所有JavaScript数据类型。
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.
这篇关于使用$ .data(" value")与$ .attr(" data-value")的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!