javascript 如何在 DIv AS HTML 内容而不是文本中显示文本区域的 HTML 内容?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/11097276/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-26 12:05:03  来源:igfitidea点击:

How can I display the HTML content of a Text Area within a DIv AS HTML content and not text?

javascriptjqueryhtmltextarea

提问by William Calleja

I have the following markup:

我有以下标记:

<input id="displayBuffer" type="hidden">
<textarea id="about" rows="2" name="about" cols="20" aria-hidden="true"><p>test</p></textarea>
<input type="button" onclick="javascript:
$('#displayBuffer').val($('#about').html());
$('#displayAbout').html(unescape($('#displayBuffer').val()));"
 name="Preview" value="Preview">

When the 'preview' button is clicked the div is populated with the content of the 'about' text area however it is not being encoded as HTML but it's displaying <p>test</p>when I want it to display testwith whatever style I have in CSS for p.

单击“预览”按钮时,div 将填充“关于”文本区域的内容,但它并未编码为 HTML,而是<p>test</p>在我希望它以test我在 CSS 中的任何样式显示时显示p

What am I doing wrong?

我究竟做错了什么?

采纳答案by Dhiraj

Something like the below should do it

像下面这样的事情应该做

$('your-container').html($('#about').val());

DEMO

演示

Hope this helps

希望这可以帮助

回答by Samich

Use .html()for placing content as html.

使用.html()将内容放置为 html。

$('#show').click(function() {
    $('#Preview').html($('#about').val());
});?

http://jsfiddle.net/LCwgc/1/

http://jsfiddle.net/LCwgc/1/

回答by Cranio

<textarea id="about" rows="2" name="about" cols="20" aria-hidden="true"><p>test</p></textarea>
<div id='displayAbout'>ale</div>
<input type="button" id='preview' name="Preview" value="Preview">????????????????????????????????

Buffer is useless:

缓冲区没用:

$("#preview").click(function() {$('#displayAbout').html($('#about').val());});

回答by Jukka K. Korpela

By HTML syntax, a textareaelement must not contain markup, only text. You need a different approach, probably an element (e.g., div) with the contenteditableattribute.

根据 HTML 语法,textarea元素不能包含标记,只能包含文本。您需要一种不同的方法,可能是一个div具有contenteditable属性的元素(例如,)。