使用jQuery转义文本追加?

Rog*_*mbe 19 javascript jquery

我知道我可以$.html用来设置某些内容的HTML内容,并$.text设置内容(并且这会转义HTML).

不幸的是,我正在使用$.append,它不会逃避HTML.

我有这样的事情:

function onTimer() {
    $.getJSON(url, function(data) {
        $.each(data, function(i, item) {
           $('#messages').append(item);
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

... url返回一个字符串数组.不幸的是,如果其中一个字符串是(例如)<script>alert('Hello')</script>,则会执行此操作.

如何让它逃脱HTML?

Pao*_*ino 29

看看jQuery是如何做到的:

text: function( text ) {
    if ( typeof text !== "object" && text != null )
        return this.empty().append( (this[0] && this[0].ownerDocument || document).createTextNode( text ) );

    var ret = "";

    jQuery.each( text || this, function(){
        jQuery.each( this.childNodes, function(){
            if ( this.nodeType != 8 )
                ret += this.nodeType != 1 ?
                    this.nodeValue :
                    jQuery.fn.text( [ this ] );
        });
    });

    return ret;
},
Run Code Online (Sandbox Code Playgroud)

所以这样的事情应该这样做:

$('#mydiv').append(
    document.createTextNode('<b>Hey There!</b>')
);
Run Code Online (Sandbox Code Playgroud)

编辑:关于你的例子,它很简单:

$('#messages').append(document.createTextNode(item));
Run Code Online (Sandbox Code Playgroud)

  • 谢谢!现在我知道jQuery没有任何等价于document.createTextNode() (3认同)

Mat*_*att 8

您是否附加了已包含内容的元素?或者您在追加后添加内容?无论哪种方式,您仍然需要对该元素执行.text(...).

如果你使用append并传递HTML作为参数,那么首先尝试创建元素,然后将其传递给append.

例如:

$('<div/>').text('your content here').appendTo('div#someid')
Run Code Online (Sandbox Code Playgroud)