分配存储在jQuery.data()中的对象的各个键 [英] Assigning individual keys of object stored in jQuery.data()
问题描述
我使用 jQuery.data()方法将自定义数据存储在元素上.
I have custom data stored on elements using jQuery.data() method.
<div id="mydiv" data-test='{"1":"apple", "2":"banana"}'>Custom data</div>
我知道我可以使用
$('#mydiv').data('test')["1"]
但是可以重新分配 单个键这样可以吗?它有效,但没有记录.其次,在使用浏览器的开发人员工具检查元素时,在这种情况下,我仍然看到旧值,即苹果". JSFiddle
But is it ok to re-assign individual keys like this ? It works but it isn't documented. Secondly, on inspecting the element using browser's developer tools, I still see the old value i.e. "apple" in this case. JSFiddle
$('#mydiv').data('test')["1"] = "pear"
更新 -找到了更多相关的问答(不是真正的重复,因为我的主要问题是关于分配对象的各个键)
Update - Found more related Q&A (not really duplicate because my primary question was about assigning individual keys of the object)
- 无法使用jQuery Data()API设置数据属性
- 为什么不更改为jQuery $ .fn.data()会更新相应的html 5 data- *属性?
- 无法更新数据属性值:有关答案的评论很好地讨论了
- Unable to set data attribute using jQuery Data() API
- Why don't changes to jQuery $.fn.data() update the corresponding html 5 data-* attributes?
- Can't update data-attribute value : Good discussion in comments of answers
推荐答案
使用.data()
设置值,在检查元素时不会更改元素中的值,它会在内部存储该数据.如果您想将这些更改反映给DOM元素,则应使用.attr()
这样的
Using .data()
to set a value, won't change the values in the element while you inspect it, it would store that data internally. If you want to reflect those changes to the DOM element, then you should use .attr()
like this,
$('#mydiv').data('test')["1"] = "pear"
$('#mydiv').attr('data-test', JSON.stringify($('#mydiv').data('test')));
演示
检查该特定元素以验证更改.
DEMO
Inspect that particular element to verify the changes.
这篇关于分配存储在jQuery.data()中的对象的各个键的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!