admin管理员组

文章数量:1353255

I was wondering if it is possible to store multiple key/values inside a data-attr like:

​<a href="#" data-social="network:facebook; socialId:123456789" id="facebook">Facebook</a>

and then when using them in my script just pick at them like $('#facebook').data('social.socialId'); or something like that instead of having to break each of them up into their own attribute?

I was wondering if it is possible to store multiple key/values inside a data-attr like:

​<a href="#" data-social="network:facebook; socialId:123456789" id="facebook">Facebook</a>

and then when using them in my script just pick at them like $('#facebook').data('social.socialId'); or something like that instead of having to break each of them up into their own attribute?

Share Improve this question edited Dec 31, 2012 at 11:49 Gabriele Petrioli 196k34 gold badges271 silver badges328 bronze badges asked Dec 31, 2012 at 11:43 stylerstyler 16.5k25 gold badges85 silver badges139 bronze badges 0
Add a ment  | 

4 Answers 4

Reset to default 13

You don't need to restrict it either to only one data-* attribute. You can always use as many as you need.

​<a href="#" data-social-network="facebook" data-social-id="123456789" id="facebook">Facebook</a>

var socialId = $('#facebook').data('social-id');

But, if you still insist. It is possible to store a JSON string and parse it.

​<a href='#' data-social='{ "network": "facebook", "socialId": 123456789 }' id='facebook'>Facebook</a>

var socialId = $('#facebook').data('social').socialId;

The JSON Object is automatically parsed by jQuery.

you could store data in JSON format in the attribute like

<div id="myElement" data-json='["value1", "value2", "value3"]'></div>​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​

and then retrieve it like

var data = JSON.parse($('#myElement').attr('data-json')​);

Store them as an object.

$('#facebook').data('social', { network: 'facebook', socialId: 12345679 });

You can use JSON and that's automatically parsed, I believe

​<a href="#" data-social="{network:facebook; socialId:123456789}" id="facebook">Facebook</a>

Would make possibilities for

$('#facebook').data('social').socialId;

本文标签: javascriptis it possible to store multiple keyvalues inside 1 data attributeStack Overflow