本文介绍了存储和使用HTML标签的数据和jQuery使用数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图存储的HTML数据标签阵列。例如:

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

<div data-locs="{'name':'London','url':'/lon/'},{'name':'Leeds','url':'/lds'}">

我使用jQuery访问这些数据。我意识到,这是存储为一个字符串,我已经试过各种方法将其转换为一个数组,但我已经碰了壁。如果您在本页面的jsfiddle看一看,你会看到什么,我试图做一个完整的例子。

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.

任何想法?

谢谢!

推荐答案

如果您使用有效的JSON( [] 为阵,双引号,而不是单一的),像这样的:

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

测试它。

这篇关于存储和使用HTML标签的数据和jQuery使用数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-30 18:52