【问题标题】:jQuery 'HTML function doesn't work with special charactersjQuery 'HTML 函数不适用于特殊字符
【发布时间】:2017-07-14 11:22:42
【问题描述】:

我正在尝试将字符串 "{<A+_2OF3_MSF}" 传递给 jQuery 的 HTML 函数。由于特殊字符<,它不起作用。我尝试使用此 escapeHtml 函数对 HTML 标记进行编码/转义,但之后我面临另一个问题。

var escapeHtml = function(theString) {
            return theString.replace(/&/g,'&amp;').replace(/</g,'&lt;').replace(/>/g,'&gt;');
        };

它将 HTML 编码的字符串附加为文本,而不是 HTML。我看到了下面的 Stack Overflow 帖子,但它建议在编码后对其进行解码。如果我这样做,我会回到原点。

Appending HTML-encoded string as HTML, not as text

我已经创建了一个小提琴:

https://jsfiddle.net/1aktfzm8/

【问题讨论】:

  • 不要那样做。你应该使用text,而不是html
  • 感谢@SLaks!我试过了,但它对我不起作用。我有一个 .css('someClass').html(formattedData) .appendTo(container); text() 函数不适合这里。我收到错误消息。

标签: javascript jquery


【解决方案1】:

您需要使用.text() 而不是.html()

$(document).ready(function(){
    $("button").click(function(){
        $("p").html("<span id=\"span\"> {A+_\"2OF3_MSF\"} </span>");
        $('#span').text();
    });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button>Change content of all p elements</button>
<p>This is a paragraph.</p>
<p>This is another paragraph.</p>

【讨论】:

  • 这对我不起作用。我有一个 .css('someClass').html(formattedData) .appendTo(container); text() 函数不适合这里。我收到错误消息。
  • 你能详细说明一下吗?
  • 字符串可以是 html {A+_2OF3_MSF} 。 text() 会起作用吗?
  • 是的!为什么不?检查了它。此外,如果该字符串中有任何额外的引号,那么您需要通过在其前面放置一个反斜杠 `\` 来对其进行转义。
  • @siam .text() 将删除我相信的 HTML 标签和 HTML 实体。
【解决方案2】:

这段代码运行正常:https://jsfiddle.net/kilotonna/eg4be1gr/1/

$(document).ready(function(){
    $("button").click(function(){
        $("p").html("{<A+_2OF3_MSF}".replace(/</g, '&lt;'));
    });
});

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-06-24
    • 2014-08-09
    • 2016-03-03
    • 1970-01-01
    • 2016-09-13
    • 2019-09-17
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多