使用 HTML 数据标记和 jQuery 存储和使用数组 [英] Store and use an array using the HTML data tag and jQuery

查看:61
本文介绍了使用 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.

http://jsfiddle.net/B4vFQ/

有什么想法吗?

谢谢!

推荐答案

如果您使用有效的 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"}]'>

然后你所拥有的(使用.data())来获取数组将起作用:

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

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

你可以在这里测试.

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

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆