如何使用jQuery追加/预置/创建文本节点 [英] How to append/prepend/create a text node with jQuery

查看:168
本文介绍了如何使用jQuery追加/预置/创建文本节点的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述


可能重复:

使用jQuery追加转义文本?

我的HTML有点像这样:

My HTML is somewhat like this:

<div id="selector">Hello World</div>

现在我想在这个div中添加一些文字。我知道我可以简单地使用

Now I'd like to append some text to this div. I know that I could simply use

$('#selector').append(text);

但这不会逃避 text 。另一种方法是将文本包装在一个范围内:

but this wouldn't escape any special characters in text. Another way is to wrap the text in a span:

$('#selector').append( $('<span>').text(text) );

但这很难看,因为它会产生不必要的标记。所以我目前的解决方案是手动创建一个TextNode:

But this is ugly, because it creates unnecessary markup. So my current solution is to manually create a TextNode:

$('#selector').append( document.createTextNode(text) );

我想知道是否有任何 jQuery-style 方式来做到这一点?

I was wondering whether there is any jQuery-style way to do this?

推荐答案

createTextNode 方法可能是最好的方法。如果你想要一个jQuery-ish语法,你可以制作一个插件。

The createTextNode approach is probably the best way to go. If you want to have a jQuery-ish syntax, you could make a plugin.

$.fn.appendText = function(text) {
    return this.each(function() {
        var textNode = document.createTextNode(text);
        $(this).append(textNode);
    });
};

这篇关于如何使用jQuery追加/预置/创建文本节点的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆