开发者

jQuery Escaping HTML from a Textarea

I want to escape HTML tags to entity names, taking text from a textarea and putting the result in a second textarea such that:

开发者_如何转开发
<mytag>

becomes

&lt;mytag&gt;

I'm using .html() and .text() going back and forth OK. My problem is dealing with the textarea element, which acts a little different.

It works fine if I first place the text into a div:

var htmlStr = $('#textareaInput').val(); //doesn't like .html() .text() ?
$('#dummy').text(htmlStr); // an object to hold the text that supports .html() 
$('#textareaOutput').val($('#dummy').html());

But I want to do something more straightforward like this:

var htmlStr = $('#textareaInput').val(); 
$('#textareaOutput').val($(htmlStr).html());

I guess my problem is that I don't understand how to manipulate jQuery objects, like strings, without manipulating DOM elements -because right now I'm using a div because it has the .html() method.

Any help would be fantastic!

Thanks.


try

var htmlStr = $('#textareaInput').val(); 
$('#textareaOutput').val($('<div/>').text(htmlStr).html());
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜