使用 HTML 数据标记和 jQuery 存储和使用数组
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4287462/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Store and use an array using the HTML data tag and jQuery
提问by will
I am attempting to store an array in the HTML data tag. For example:
我试图在 HTML 数据标签中存储一个数组。例如:
<div data-locs="{'name':'London','url':'/lon/'},{'name':'Leeds','url':'/lds'}">
I am accessing that data using jQuery. I realise that this is stored as a string, and I've tried various methods to convert it to an array, but I've hit a wall. If you take a look at this jsFiddle page you'll see a full example of what I'm trying to do.
我正在使用 jQuery 访问该数据。我意识到这是作为字符串存储的,并且我尝试了各种方法将其转换为数组,但我遇到了障碍。如果您查看这个 jsFiddle 页面,您将看到我正在尝试做的完整示例。
Any ideas?
有任何想法吗?
Thanks!
谢谢!
回答by Nick Craver
If you use valid JSON ([
and ]
for the array, double quotes instead of single), like this:
如果您使用有效的JSON([
和]
为阵,双引号,而不是单一的),就像这样:
<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:
然后你所拥有的(使用.data()
)来获取数组将起作用:
$('#locations').data('locations');
回答by jwueller
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.
尝试添加[
和]
开始和结束(这使它成为有效的 JSON)。这样做之后,您可以使用JSON.parse()
将其转换为原生 JavaScript 对象。
回答by cambraca
Try this:
尝试这个:
var testOne = eval("new Array(" + $('#locations').data('locations') + ")");
Look at it in jsfiddle.
在jsfiddle 中查看它。