将textarea值复制到div中,并保留换行符和html作为文本 [英] Copy a textarea value into a div keeping line breaks and html as text

查看:459
本文介绍了将textarea值复制到div中,并保留换行符和html作为文本的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在努力寻找一种方法,使文本区域中的任何内容都可以通过单击按钮移到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, '&lt;')
    .replace(/>/g,'&gt;')
    .replace(/\n/g, '<br/>');

这篇关于将textarea值复制到div中,并保留换行符和html作为文本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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