如何在 jQuery 中添加文本(不是 HTML)?
我意识到我可以使用以下方法在元素前面添加内容:
$(...).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 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
您可以创建一个文本节点并将内容放在那里并
前置
:例如:http:// /jsfiddle.net/niklasvh/gCKHe/
You can create a textnode and put the contents there and
prepend
that:example: http://jsfiddle.net/niklasvh/gCKHe/
您可以使用
text
函数代替prepend
,只需将原始文本添加到新文本的末尾:$("#elementID").text ("" + $("#elementID").text());
You can use the
text
function instead ofprepend
, and simply add the original text to the end of the new text:$("#elementID").text("<span>" + $("#elementID").text());
在我看来,HTML 实体是可以的:
您可以使用 http://debuggable.com/posts/encode-html-entities-with-jquery:480f4dd6-13cc-4ce9-8071-4710cbdd56cb
如果你还想创建PHP的函数 htmlentities 在 Javascript 中,您可以使用 PHP-JS 项目中提供的代码:http://phpjs.org/functions/htmlentities:425
或者您可以通过将前面的提示包含在内来简化函数:
在这两种情况下,您都可以使用 htmlentities 函数,如下所示:
HTML entities are ok, in my opinion:
You may automate the entities with the tip found at http://debuggable.com/posts/encode-html-entities-with-jquery:480f4dd6-13cc-4ce9-8071-4710cbdd56cb
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:
In both cases, you would use the htmlentities function like this:
您可以实现 HTML 编码(和解码)功能,就像这个接受的答案: HTML-encoding loss when attribute read from输入字段
,然后执行:
You could implement HTML encode (and decode) functions, like this accepted answer: HTML-encoding lost when attribute read from input field
and then do: