javascript 附加 HTML 转义文本:jQuery

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/11957529/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-26 14:52:38  来源:igfitidea点击:

Append HTML-escaped text: jQuery

javascriptjqueryhtmldomescaping

提问by Nathan Friend

I'm used to using jQuery's .append()method to add text or HTML onto the end of a pre-existing element. I'm currently using jQuery's .text()to escape strings that could potentially contain HTML. Unfortunately, there doesn't seem to be a jQuery method that will append the results of the .text()method to an element instead of replacing its contents.

我习惯于使用 jQuery 的.append()方法将文本或 HTML 添加到预先存在的元素的末尾。我目前正在使用 jQuery.text()来转义可能包含 HTML 的字符串。不幸的是,似乎没有一种 jQuery 方法可以将方法的结果附加.text()到元素而不是替换其内容。

Is there a way to append, instead of replace, this escaped text to an element? Or is there a better way to escape strings containing HTML?

有没有办法将这个转义文本附加到元素而不是替换?或者有更好的方法来转义包含 HTML 的字符串吗?

Thanks.

谢谢。

- EDIT -

- 编辑 -

A little more context: I'm building an HTML string dynamically, and so I'll need to be able to add multiple elements with escaped content programmatically.

更多上下文:我正在动态构建一个 HTML 字符串,因此我需要能够以编程方式添加多个带有转义内容的元素。

采纳答案by Jo?o Silva

You could create a dummy element to hold the result of .text()which can then be appended to your destination element:

您可以创建一个虚拟元素来保存其结果,.text()然后可以将其附加到您的目标元素:

$('<div/>').text('your <span>html</span> string').appendTo(...);

回答by

As I have tried many ways, I think the following method is the cleanest way to add text to whatever node you want. no stock tag needed, only plain text, which will help to avoid potential problems

由于我尝试了很多方法,我认为以下方法是将文本添加到您想要的任何节点的最干净的方法。不需要股票标签,只有纯文本,这将有助于避免潜在问题

$(document.createTextNode("SomePlainText")).appendTo(p);

回答by KRyan

You could just use

你可以用

$(whatever).text($(whatever).text() + whatever_you_want_to_append);

EDIT for the fiddle in my comment, try this:

编辑我评论中的小提琴,试试这个:

for ( /* some looping parameters */ ) {
    $('<li></li>') // create an li
        .text(stringWithHtml) // pass it the text, as text not html
        .appendTo('#thisIsWhatINeed'); // append it where you want it
}

jsFiddle

js小提琴