jQuery从Textarea转义HTML [英] jQuery Escaping HTML from a Textarea

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

问题描述

我想将HTML标签转义为实体名称,从 textarea 取文本,并将结果放入第二个 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;

我使用 .html() .text()来回确定。我的问题是处理 textarea 元素,它有点不同。

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

如果我第一次放置将文本转换为div:

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());

我猜我的问题是我不明白如何操纵jQuery对象,比如字符串,而没有操作DOM元素 - 因为现在我正在使用div,因为它有 .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.

任何帮助都会很棒!

谢谢。

推荐答案

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

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

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