How do you push a value to a jQuery data() object from an element? -
suppose have this:
<a href="#" data-mydata="{'key':[value1, value2, value3]}">link</a>
and somewhere in javascript when reading/checking data want push more values 'key.'
this not work:
var mykey = $('a').data('mydata').key; $('a').data('mydata', mykey.push('value4'));
this doesn't work either:
var mykey = $('a').data('mydata').key; $('a').data('mydata.key', mykey.push('value4'));
i haven't found work either:
var mykey = $('a').data('mydata').key; $('a').data('mydata', '{"key":'+mykey.push('value4')+'}');
i must missing here.
just update mykey
directly:
var mykey = $('a').data('mydata').key; mykey.push('value4'); console.log(mykey); // ["value1", "value2", "value3", "value4"] console.log($('a').data('mydata').key)// ["value1", "value2", "value3", "value4"]
note: fixed data attribute have valid json jquery can parse object properly. wrapped values in quotes.
Comments
Post a Comment