jQuery的data(key,val)和attr(data-key,data-val)有什么区别 [英] What's the difference between jquery's data(key,val) and attr(data-key,data-val)
问题描述
如果尝试使用data()
方法更改数据属性值,则不会获得与attr(data-key, data-value)
方法相同的结果.
If you try to change a data attribute value with data()
method you don't get the same result as attr(data-key, data-value)
method.
例如,我正在使用data-hovered=true
来存储元素的某些状态.如果element[data-hovered=true]
选择器具有某些CSS样式,则使用data()
方法将值true
设置为data-hovered
无效.仅使用attr()
才有效.
For example, I'm using data-hovered=true
to store some state for the element. If you have some css styling for the element[data-hovered=true]
selector, using data()
method to assing the value true
to data-hovered
won't have effect. Only using attr()
this would have effect.
那么这两种方法有什么区别?
So what's the difference between these two methods?
推荐答案
.data()用于将数据存储在对象中,但是从HTML5的发行版"开始,它也可以访问元素上的data- *属性
.data() is used to store data in an object, but as of the "release" of HTML5, it can also access data-* attributes on elements.
但是,它不能更改它们,因为它主要用于将数据存储在对象等中,而不是物理地存储在元素上.
However, it can not change these, as it is primarily used for storing data in objects etc, not physically on elements.
因此,attr()是更改元素上的属性值(例如data- *属性)的唯一方法.
Therefore attr() is the only way to change a value of an attribute on an element, such as data-* attributes.
请参阅:
- jQuery Data vs Attr?
- http://api.jquery.com/jQuery.data/
- http://api.jquery.com/attr/
这篇关于jQuery的data(key,val)和attr(data-key,data-val)有什么区别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!