javascript - 数据属性上的 Json
问题描述
大家好,我在数据属性中有一个 json,我必须获取其中的数据,我可以获取数据属性中的字符串,但我无法访问该对象。
这是我的代码:
HTML
<a data-password="{Show:'Show', Hide:'Hide'}">Show</a>
JS
$(document).ready(function() {
$("a[data-password]").click(function(e) {
var lJson = $(this).attr("data-password");
console.log(lJson);
lJson2 = JSON.parse(lJson);
console.log(lJson2.Hide);
});
});
解决方案
问题是数据属性中的 JSON 未正确字符串化。
字符串化版本应该看起来像{"Show":"Show", "Hide":"Hide"}
双引号内的键和字符串值。
试试下面这个例子的工作版本:
$(document).ready(function() {
$("a[data-password]").click(function(e) {
var lJson = $(this).attr("data-password");
console.log(lJson);
lJson2 = JSON.parse(lJson);
console.log(lJson2.Hide);
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<a data-password='{"Show":"Show", "Hide":"Hide"}'>Show</a>
推荐阅读
- mysql - ,class varchar(2) NOT NULL 错误代码 1064
- dll - 参考外部 DLL 编译 c# 项目时出错
- xamarin - DisplayAlert 导致 Xamarin 应用程序崩溃
- mysql - 建立主键时连接丢失。修复还是弃坑?
- node.js - 对等依赖的对等依赖
- javascript - 如何比较什么人类型?如果 char 等于 char 那样做
- c# - 如何在序列化期间不擦除文件中的数据?
- mysql - 两个查询的总和
- hadoop - 大数据存储和查询与传统关系/非关系数据库
- api - Fortify API Start Scan with Default - 如何发送包裹