[英]Json on data-attribute
Hi everyone I have a json in a data attribute and I have to take the data that is inside, I can get the string inside the data attribute but I can't get access to the object.大家好,我在数据属性中有一个 json,我必须获取其中的数据,我可以获取数据属性中的字符串,但无法访问该对象。
This is my code:这是我的代码:
HTML HTML
<a data-password="{Show:'Show', Hide:'Hide'}">Show</a>
JS 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);
});
});
The issue is that the JSON inside of your data attribute is not properly stringified .问题是数据属性中的 JSON 没有正确字符串化。
The stringified version should look like {"Show":"Show", "Hide":"Hide"}
with the keys and string values inside double quotes.字符串化的版本应该看起来像
{"Show":"Show", "Hide":"Hide"}
键和字符串值在双引号内。
Try this example below for the working version:在下面的工作版本中试试这个例子:
$(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>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.