javascript - 当 JSON 从数据属性读取时,HTML 实体转换为其字符值

标签 javascript json custom-data-attribute

我正在尝试访问数据属性中的字符串化 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 &quot;Still Dreaming: Frances Walker at 93&quot;"]'></div>

最佳答案

Why did JavaScript convert &quot; 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/

相关文章:

Javascript访问父公共(public)变量

javascript - 如何根据 JavaScript 中的键名称比较两个 JSON 值?

javascript - 使用 Tempo 转换树结构

javascript - 从单个 HTML5 "data-"属性创建一个数组

javascript - jQuery:选择不为空的数据属性?

javascript - 随机函数触发 $digest() 错误

javascript - 将鼠标悬停在一个 div 上会触发其他 div 悬停在其中

javascript - 光滑 slider 中心模式

json - compoundJS::如何创建模式来反射(reflect)半复杂的 JSON 对象?

javascript - 将参数从 <div> 的 data-options 属性传递到 JavaScript 函数并进行解析