如何在 jQuery 中添加文本(不是 HTML)?

发布于 2024-11-16 09:36:58 字数 254 浏览 7 评论 0原文

我意识到我可以使用以下方法在元素前面添加内容:

$(...).prepend(myText);

但是,如果 myText 是,比方说,"",我实际上希望该文本出现,但 .prepend() 会在前面添加一个空的 span 元素。解决这个问题的推荐方法是什么?我真的必须手动对文本进行 HTML 转义吗?还是有更优雅的方法?

I realise that I can prepend stuff to an element using:

$(...).prepend(myText);

However, if myText is, let’s say, "<span>", I actually want that text to appear, but .prepend() would instead prepend an empty span element. What is the recommended way to solve this? Do I really have to HTML-escape the text manually or is there something more elegant?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

缘字诀 2024-11-23 09:36:58

您可以创建一个文本节点并将内容放在那里并前置

$('div').prepend(document.createTextNode("<span>"));

例如:http:// /jsfiddle.net/niklasvh/gCKHe/

You can create a textnode and put the contents there and prepend that:

$('div').prepend(document.createTextNode("<span>"));

example: http://jsfiddle.net/niklasvh/gCKHe/

过潦 2024-11-23 09:36:58

您可以使用 text 函数代替 prepend,只需将原始文本添加到新文本的末尾:

$("#elementID").text ("" + $("#elementID").text());

You can use the text function instead of prepend, and simply add the original text to the end of the new text:

$("#elementID").text("<span>" + $("#elementID").text());

我做我的改变 2024-11-23 09:36:58

在我看来,HTML 实体是可以的:

$(...).prepend('<span>');

您可以使用 http://debuggable.com/posts/encode-html-entities-with-jquery:480f4dd6-13cc-4ce9-8071-4710cbdd56cb

$(...).prepend($('<div/>').text('<span>').html());

如果你还想创建PHP的函数 htmlentities 在 Javascript 中,您可以使用 PHP-JS 项目中提供的代码:http://phpjs.org/functions/htmlentities:425

或者您可以通过将前面的提示包含在内来简化函数:

function htmlentities(string) {
  return $('<div/>').text(string).html();
}

在这两种情况下,您都可以使用 htmlentities 函数,如下所示:

$(...).prepend(htmlentities('<span>'));

HTML entities are ok, in my opinion:

$(...).prepend('<span>');

You may automate the entities with the tip found at http://debuggable.com/posts/encode-html-entities-with-jquery:480f4dd6-13cc-4ce9-8071-4710cbdd56cb

$(...).prepend($('<div/>').text('<span>').html());

If you also want to create PHP's function htmlentities in Javascript, you may use the code available at PHP-JS project: http://phpjs.org/functions/htmlentities:425

Or you may simplify by wrapping the previous tip in a function:

function htmlentities(string) {
  return $('<div/>').text(string).html();
}

In both cases, you would use the htmlentities function like this:

$(...).prepend(htmlentities('<span>'));
帅哥哥的热头脑 2024-11-23 09:36:58

您可以实现 HTML 编码(和解码)功能,就像这个接受的答案: HTML-encoding loss when attribute read from输入字段

,然后执行:

$(...).prepend(htmlEncode(myText));

You could implement HTML encode (and decode) functions, like this accepted answer: HTML-encoding lost when attribute read from input field

and then do:

$(...).prepend(htmlEncode(myText));
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文