gpt4 book ai didi

javascript - 在 JSON 对象上使用 stringify 以在 HTML 数据属性中使用

转载 作者:行者123 更新时间:2023-12-01 01:31:19 25 4
gpt4 key购买 nike

我一直在浏览 stringify 上的各种帖子,但一直无法找到问题的解决方案。

我正在尝试对 JSON 对象进行字符串化并将其插入到 DOM 中新元素的数据属性中。

在下面的示例中,如果使用 Chrome 检查元素,然后选择编辑 HTML,则输出如下所示:

<div class="ui-menu-item" data-menu-item="{" title":"this="" is="" a="" test="" for="" \"="" and="" '.="" it="" fails.","url":"some="" url"}"="" id="test">This element contains the data.</div>

我认为所需的结果应该如下所示:

<div class="ui-menu-item" data-menu-item="{&quot;title&quot;:&quot;this is a test for &quot; and ' it fails.&quot;,&quot;url&quot;:&quot;some url&quot;}" id="test">This element contains the data.</div>

注意:我知道我可以使用 jQuery 的数据方法,但选择不这样做。

  var data = {
title: 'This is a test for " and \'. It fails.',
url: 'Some url'
};

data = JSON.stringify(data);

console.log (data);

$(document).ready(function() {
var tpl = "<div class=\"ui-menu-item\" data-menu-item=\"" + data + "\" id=\"test\">This element contains the data.</div>";

$('body').append(tpl);
});
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
</head>
<body>
</body>
</html>

最佳答案

  var data = {
title: 'This is a test for " and \'. It fails.',
url: 'Some url'
};

data = JSON.stringify(data);

console.log (data);

$(document).ready(function() {
var tpl = "<div class=\"ui-menu-item\" id=\"test\">This element contains the data.</div>";

$('body').append(tpl);
$('#test').attr('data-menu-item', data)
});
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
</head>
<body>
</body>
</html>

关于javascript - 在 JSON 对象上使用 stringify 以在 HTML 数据属性中使用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53249605/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com