Store and use an array using the HTML data tag and jQuery

后端 未结 3 2066
一生所求
一生所求 2020-12-05 02:07

I am attempting to store an array in the HTML data tag. For example:

相关标签:
3条回答
  • 2020-12-05 02:34

    If you use valid JSON ([ and ] for the array, double quotes instead of single), like this:

    <div id="locations" data-locations='[{"name":"Bath","url":"/location/bath","img":"/thumb.jpg"},{"name":"Berkhamsted","url":"/location/berkhamsted","img":"/thumb.jpg"}]'>
    

    Then what you have (using .data()) to get the array will work:

    $('#locations').data('locations');
    

    You can test it here.

    0 讨论(0)
  • 2020-12-05 02:54

    Try adding [ and ] to beginning and end (this makes it valid JSON). After doing so, you can use JSON.parse() to convert it to a native JavaScript object.

    0 讨论(0)
  • 2020-12-05 02:56

    Try this:

    var testOne = eval("new Array(" + $('#locations').data('locations') + ")");
    

    Look at it in jsfiddle.

    0 讨论(0)
提交回复
热议问题