使用jQuery包含“获取数据属性”

时间:2016-06-16 11:37:52

标签: javascript jquery json

当使用jQuery的.data()获取data-Attributes并且此data-attribute包含双引号的HTML-Entity时,它无法将其转换为JSON-Object。如下所示,它被简单地视为无效的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 &quot;value&quot; in quotes"
                    }'></div>

<div data-someprop2='{ "key": "some &quot;value&quot; 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-Objects传递双引号?

编辑:添加了第三个示例,表明它不是换行符。

1 个答案:

答案 0 :(得分:0)

问题似乎是由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='{&quot;key&quot;: &quot;some value without quotes&quot;}'></div>
<div data-someprop2='{ "key": "some &quot;value&quot; in quotes" }'></div>
<div data-someprop3='{ "key": "some &nbsp;value&nbsp; in quotes" }'></div>
<div data-someprop4='{ 
    "key": "some &nbsp;value&nbsp; in quotes" 
}'></div>


<div class="target1"></div>
<div class="target2"></div>
<div class="target3"></div>
<div class="target4"></div>