简体   繁体   English

在textarea中使用.val()时保留换行符和回车字符 - Jquery

[英]Preserve line breaks and carriage return characters when using .val() in textarea - Jquery

I have this html -: 我有这个HTML - :

<div id="myEditor" contenteditable="true"></div>
<textarea id="myArea"></textarea>

I have this jquery code -: 我有这个jquery代码 - :

$("#myEditor").live("paste",function(){ 
var $this = $(this); 

setTimeout(function(){ $("#myArea").val($this.text()); },2);
                                     });

But when i use the above jquery code, all the line breaks and carriage returns are stripped off. 但是当我使用上面的jquery代码时,所有的换行符和回车都被剥离了。

From Jquery documentation, I even tried using this , but in vain -: 从Jquery文档中,我甚至尝试过使用它,但是徒劳 - :

$.valHooks.textarea = {
get: function( elem ) {
return elem.value.replace( /\r?\n/g, "\r\n" );
}                     };

But when I manually copy everything from div and paste it into textarea, line breaks are well preserved.. 但是当我手动复制div中的所有内容并将其粘贴到textarea中时,换行符保存完好。
How do go about this issue. 怎么办这个问题。 Thanks 谢谢

Try this 尝试这个

$.valHooks.textarea = {
get: function( elem ) {
return elem.value.replace( /\r?\n/g, "<br />" );
}                     };

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM