使用HTML数据标记和jQuery存储和使用数组

时间:2022-12-08 10:30:02

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页面,你会看到一个完整的示例。

http://jsfiddle.net/B4vFQ/

http://jsfiddle.net/B4vFQ/

Any ideas?

什么好主意吗?

Thanks!

谢谢!

3 个解决方案

#1


71  

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

如果对数组使用有效的JSON ([and]),则双引号而不是单引号,如下所示:

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

You can test it here.

你可以在这里测试。

#2


4  

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对象。

#3


-2  

Try this:

试试这个:

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

Look at it in jsfiddle.

看看jsfiddle。

#1


71  

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

如果对数组使用有效的JSON ([and]),则双引号而不是单引号,如下所示:

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

You can test it here.

你可以在这里测试。

#2


4  

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对象。

#3


-2  

Try this:

试试这个:

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

Look at it in jsfiddle.

看看jsfiddle。