将textarea值复制到div中,并保留换行符和html作为文本 [英] Copy a textarea value into a div keeping line breaks and html as text
问题描述
我正在努力寻找一种方法,使文本区域中的任何内容都可以通过单击按钮移到div上.我要寻找的一些关键功能是希望保留换行符,并且如果用户输入任何类型的html标签,它将以相同的方式显示.
I am working on trying to get a way for whatever is in a textarea to move over to a div on a button click. Some of the key features that i am looking for is that i want linebreaks to stay and that if a user inputs any kind of html tags, it will cross over shown the same way.
这样输入的内容:
<body>
<p>blah blah blah</p>
<p>more text</p>
</body>
在div区域中仍然看起来相同.
will still look the same in the div area.
我尝试了几件事,但是最近我尝试了:
I have tried a couple of things, but most recently I have tried this:
var value = $('#selector-input textarea').val().replace(/\n/g, '<br/>');
$('#selector-canvas #canvas').text(value);
有人有什么想法吗?任何帮助将非常感激.谢谢!
Does anyone have any ideas? Any help would be much appreciated. Thanks!
推荐答案
If you want to preserve the tags you have to replace the angle brackets first, followed by replacing the newline characters - http://jsfiddle.net/jayblanchard/2Kg9F/
var value = $('textarea').val()
.replace(/</g, '<')
.replace(/>/g,'>')
.replace(/\n/g, '<br/>');
这篇关于将textarea值复制到div中,并保留换行符和html作为文本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!