Assigning individual keys of object stored in jQuery.data()

一个人想着一个人 提交于 2019-12-11 05:04:10

问题


I have custom data stored on elements using jQuery.data() method.

<div id="mydiv" data-test='{"1":"apple", "2":"banana"}'>Custom data</div>

I know I can access individual keys of the object stored in data-test using

    $('#mydiv').data('test')["1"]

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)

  • 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

回答1:


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.




回答2:


Try this

$('#mydiv').data('test')["1"] = "pear";
$('#mydiv').attr('data-test',function(_,attr){
   return JSON.stringify(attr);
});


来源:https://stackoverflow.com/questions/24837471/assigning-individual-keys-of-object-stored-in-jquery-data

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