使用jQuery转义文本追加? [英] Escaping text with jQuery append?

查看:328
本文介绍了使用jQuery转义文本追加?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I know that I can use $.html to set the HTML content of something, and $.text to set the content (and that this escapes the HTML).

不幸的是,我正在使用 $。追加 ,它不会逃避HTML。

Unfortunately, I'm using $.append, which doesn't escape the HTML.

我有这样的事情:

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

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

...where the url returns an array of strings. Unfortunately, if one of those strings is (e.g.) <script>alert('Hello')</script>, this gets executed.

如何让它逃脱HTML?

How do I get it to escape HTML?

推荐答案

查看jQuery是如何做到的:

Check out how jQuery does it:

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;
},

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

So something like this should do it:

$('#mydiv').append(
    document.createTextNode('<b>Hey There!</b>')
);

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

EDIT: Regarding your example, it's as simple as:

$('#messages').append(document.createTextNode(item));

这篇关于使用jQuery转义文本追加?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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