首页 > 解决方案 > 数据属性上的 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);
    });

});

标签: javascripthtmljsoncustom-data-attribute

解决方案


问题是数据属性中的 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>


推荐阅读