Assigning individual keys of object stored in jQue

2019-08-07 10:09发布

问题:

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);
});