gpt4 book ai didi

javascript - 将从元素的数据属性获得的字符串转换为json

转载 作者:行者123 更新时间:2023-11-30 12:03:31 27 4
gpt4 key购买 nike

我收到以下代码的错误。我知道 $.parseJSON() 对单引号/双引号敏感。我想不出解决这个问题的方法。你能帮忙吗?

<div data-x='{"a":"1","b":"2"}'></div>

$(document).ready(function(){
var data =$.parseJSON($("div").data("x"))
alert(data.a)
})

https://jsfiddle.net/r2Lnfbpm/

最佳答案

jQuery的data()做的是类型转换,所以当data属性是有效的JSON时,它已经被解析成一个对象,将一个对象传递给$.parseJSON产生一个错误,因为它需要一个 JSON 字符串。

$(document).ready(function(){
var data = $("div").data("x");
console.log(data.a);
});

来自documentation

Every attempt is made to convert the string to a JavaScript value (this includes booleans, numbers, objects, arrays, and null).
A value is only converted to a number if doing so doesn't change the value's representation.

For example, "1E02" and "100.000" are equivalent as numbers (numeric value 100) but converting them would alter their representation so they are left as strings. The string value "100" is converted to the number 100.

When the data attribute is an object (starts with '{') or array (starts with '[') then jQuery.parseJSON is used to parse the string; it must follow valid JSON syntax including quoted property names. If the value isn't parseable as a JavaScript value, it is left as a string.

To retrieve the value's attribute as a string without any attempt to convert it, use the attr() method.

关于javascript - 将从元素的数据属性获得的字符串转换为json,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35996081/

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