如何使用html5数据属性将javascript对象或JSON存储在html元素中? [英] How to store javascript object or JSON in html element usiing html5 data attribute?

查看:539
本文介绍了如何使用html5数据属性将javascript对象或JSON存储在html元素中?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有锚元素.我想以此方式存储和检索对象.

I have anchor element.I want to store and retrive the object in it like this way.

<a  id ="test" data-val="{key1:val1,key1:val1}"> </a>

如果我以这种方式保存,则在获取时

If I save in this way,while fetching it

$("#test").data('val')它给了我像

"{key1:val1,key1:val1}".

但是我无法再次将其解析为json or javascript object. 我尝试使用$.parseJSON()JSON.parse().但这会引发错误.

But I am unable to parse it to json or javascript object again. I have tried using $.parseJSON(),JSON.parse(). But it throwing an error.

在没有localstorage or sessionstorage o cookie

编辑:

致电$("#test").data('val')

我正在得到这样的字符串

I am getting string like this

"{'category_slug' : 'featured','tip_slug':'tip-with-all-cats'}"

如果我使用了$.parseJSON()JSON.parse(),则会引发错误

If i have use $.parseJSON()or JSON.parse() it throwing an error

Uncaught SyntaxError: Unexpected token

推荐答案

那是因为它不是有效的JSON.

That's because it's not valid JSON.

有效JSON带有引号的关键字,并使用双引号分隔字符串.您的示例不满足这些要求.

Valid JSON has quoted keys and uses double quotes to delimit strings. Your example doesn't meet these requirements.

这篇关于如何使用html5数据属性将javascript对象或JSON存储在html元素中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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