我正在尝试访问数据属性中的字符串化 JSON 数组。当我使用 $(...).data('whatever')
或 $(...).attr('data-whatever')
获取值时,但是,JSON 内容中的 HTML 实体(例如 "
)会转换为其字符表示形式(例如 "
),这会导致 JSON 字符串在解析时被误解。
例如,如果我的数据属性的值为 ["Oberlin City Club: Opera Preview","Documentary Screening "Still Dreaming: Frances Walker at 93""]
,请使用$(...).data()
返回 ["Oberlin City Club: Opera Preview","Documentary Screening "Still Dreaming: Frances Walker at 93""]
。为什么JavaScript要把"
转成"
?如何在不把"
转成"
的情况下读取数据属性?
console.log($('div').attr('data-titles'));
console.log(JSON.parse($('div').attr('data-titles')));
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div data-titles='["Oberlin City Club: Opera Preview","Documentary Screening "Still Dreaming: Frances Walker at 93""]'></div>
最佳答案
Why did JavaScript convert
"
into "?
在本例中,情况并非如此。通过在响应中使用 "
,浏览器会将其解析为 "
,这就是放入属性中的内容。这是因为您使用了 html 实体。
An HTML entity is a piece of text ("string") that begins with an ampersand (&) and ends with a semicolon (;) Entity MDN
因此,JavaScript 没有机会补救这种情况。您需要找到一种在模板引擎中以不同方式呈现 "
的方法,最好使用 "
对引用进行双重编码(如 @Barmar in comments 中所述) )。
关于javascript - 当 JSON 从数据属性读取时,HTML 实体转换为其字符值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49393561/