转义数据属性JSON对象中的引号和html

时间:2020-12-10 22:28:46

Using the HTML5 data- attribute, one can store JSON in HTML as shown in the HTML below. This works great with string key:value pairs but I can't figure out how to make the values include special characters or HTML.

使用HTML5数据属性,可以将HTML存储在HTML中,如下面的HTML所示。这适用于字符串键:值对,但我无法弄清楚如何使值包括特殊字符或HTML。

The part of the JSON object that is giving problems is this: Can't vote on <b>own</b> review (also interested in more complicated HTML chunks like this: <span style="text-decoration:underline" own</span>. Here's a JSFiddle for the code below.

给出问题的JSON对象的一部分是这样的:不能对自己的 评论投票(也对像这样的更复杂的HTML块感兴趣:。这是下面代码的JSFiddle。

JS:

$('button').on('click', function () {
  var $this=$(this), data=$this.data('data');
     $('#output').html(data.message);
});

HTML:

<button type='button' data-data='{"type": "voting", "message": "Can't vote on <span style="text-decoration:underline" own</span> review"}'></button>
<div id='output'></div>

1 个解决方案

#1


6  

You need to escape the HTML and specifically in this example, & and the character used to quote the attribute value (either " or '):

您需要转义HTML,特别是在此示例中,&和用于引用属性值的字符(“或”):

<button type='button' data-data='{"type": "voting", "message": "Can&#39;t vote on <b>own</b> review"}'></button>

or:

<button type='button' data-data='{"type": "voting", "message": "Can&#39;t vote on <span style=&#39;text-decoration:underline&#39;>own</span> review"}'></button>

#1


6  

You need to escape the HTML and specifically in this example, & and the character used to quote the attribute value (either " or '):

您需要转义HTML,特别是在此示例中,&和用于引用属性值的字符(“或”):

<button type='button' data-data='{"type": "voting", "message": "Can&#39;t vote on <b>own</b> review"}'></button>

or:

<button type='button' data-data='{"type": "voting", "message": "Can&#39;t vote on <span style=&#39;text-decoration:underline&#39;>own</span> review"}'></button>