当使用jQuery的.data()获取数据属性并且此数据属性包含双引号的HTML实体时,无法将其转换为JSON对象。如下所示,它只是被视为无效的JSON,因此将其视为字符串:
var dataAsString = $("[data-someprop]").data("someprop");
var dataAsString2 = $("[data-someprop2]").data("someprop2");
var dataAsJSON = $("[data-anotherprop]").data("anotherprop");
$(".target1").append(typeof(dataAsString));
$(".target2").append(typeof(dataAsString2));
$(".target3").append(typeof(dataAsJSON));
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div data-someprop='{
"key": "some "value" in quotes"
}'></div>
<div data-someprop2='{ "key": "some "value" in quotes" }'></div>
<div data-anotherprop='{
"key": "some value without quotes"
}'></div>
<div class="target1"></div>
<div class="target2"></div>
<div class="target3"></div>
如何在数据属性中通过JSON对象传递双引号?
编辑:添加了第三个示例来显示,它不是换行符。
最佳答案
该问题似乎是由HTML编码的JSON字符串版本中的换行引起的。以下工作正常:
var dataAsString = $("[data-someprop]").data("someprop");
var dataAsString2 = $("[data-someprop2]").data("someprop2");
var dataAsString3 = $("[data-someprop3]").data("someprop3");
var dataAsString4 = $("[data-someprop4]").data("someprop4");
$(".target1").append(typeof(dataAsString) + ' - ' + dataAsString.key);
$(".target2").append(typeof(dataAsString2) + ' - ' + dataAsString2.key);
$(".target3").append(typeof(dataAsString3) + ' - ' + dataAsString3.key);
$(".target4").append(typeof(dataAsString4) + ' - ' + dataAsString4.key);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div data-someprop='{"key": "some value without quotes"}'></div>
<div data-someprop2='{ "key": "some "value" in quotes" }'></div>
<div data-someprop3='{ "key": "some value in quotes" }'></div>
<div data-someprop4='{
"key": "some value in quotes"
}'></div>
<div class="target1"></div>
<div class="target2"></div>
<div class="target3"></div>
<div class="target4"></div>