Javascript textarea换行jquery

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/12079160/
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-08-23 07:04:01  来源:igfitidea点击:

textarea line break jquery

javascriptjqueryjquery-ui

提问by Viktors

I have got a button 'edit description' when I click on it text disappear and appear

当我点击它时,我有一个“编辑描述”按钮文本消失并出现

        if (id == 'commedit') jQuery(this).html('<textarea>'+jQuery(this).text()+'</textarea>');
        else if (id == 'commsave') {
            jQuery(this).text(jQuery(this).find('textarea').val());
        }

In MySql I have this text - "tetee<br>afafaf<br>afafaf<br>afsafsasfasf"in view it dispays with line breaks but when I click 'edit' in text area which come with Jquery text appear without lines and when I click save it also appear in my description field in one long line without line breaks. So I need your help

在 MySql 中,我有此文本 -"tetee<br>afafaf<br>afafaf<br>afsafsasfasf"鉴于它显示换行符,但是当我在带有 Jquery 文本的文本区域中单击“编辑”时,它会出现无行,当我单击“保存”时,它也会出现在我的描述字段中的一长行中休息。所以我需要你的帮助

回答by epascarello

<br>are html breaks. You want \nin a textarea.

<br>是 html 中断。你想要\n一个文本区域。

jQuery(this).html().replace(/<br>/gi,"\n")

When you save, you want to change it back to breaks and use html() instead of text();

保存时,您想将其改回中断并使用 html() 而不是 text();

var elem = jQuery(this);
if (id === 'commedit') {
    var text = jQuery(this).html().replace(/<br>/gi,"\n");
    elem.html('<textarea>'+ text +'</textarea>');
} else if (id === 'commsave') {
    var html = elem.find('textarea').val().replace(/\n/g,"<br>");
    elem.html(html);
}

JSFiddle Example

JSFiddle 示例