jQuery 要转换为 <br/> 的 Textarea 中的新行

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

New Line in Textarea to be converted to <br/>

jquerytextareanewlinereplacewith

提问by C_K

There's a lot of threads here about converting br/> or preserving newlines across different languages, but not many regarding textarea.

这里有很多关于在不同语言之间转换 br/> 或保留换行符的主题,但关于 textarea 的主题并不多。

I have this script:

我有这个脚本:

var boxText = "";
$("textarea.BoxText").live('dblclick', function () {
    boxText = $(this).val().replace(/ /g, "<br/>");
  $(this).replaceWith( '<div class="BoxText">' + $(this).val() + '</div>' );

});
$("div.BoxText").live('dblclick', function () {
  $(this).replaceWith( '<textarea form="HTML" class="BoxText">' + boxText + '</textarea>' );
});

I have a textarea element, editable. When the user double-clicks on it, it converts into a div. However, in a div, the newlines are not preserved. I would like to convert just the new lines into
, currently, all spaces are being converted. I have a second script that converts it back to textarea, hence the variable for storing the string. I would need the
's to be reconverted into new lines as well.

我有一个 textarea 元素,可编辑。当用户双击它时,它会转换为一个 div。但是,在 div 中,不会保留换行符。我只想将新行转换为
,目前,所有空格都被转换。我有第二个脚本将其转换回 textarea,因此是用于存储字符串的变量。我还需要将
's 重新转换为新行。

This may seem redundant, but i have a good reason for this.

这似乎是多余的,但我有充分的理由这样做。

回答by Neil

This will replace line breaks to HTML break tags. The different combinations are to cover the different browsers/systems and how line breaks are interpreted.

这会将换行符替换为 HTML 中断标记。不同的组合将涵盖不同的浏览器/系统以及如何解释换行符。

$(this).val().replace(/\r\n|\r|\n/g,"<br />")

This will bring it back to new lines - also covering how different browsers interpret innerHTML.

这将把它带回新的行——也涵盖了不同的浏览器如何解释innerHTML。

boxText.replace(/<br\s?\/?>/g,"\n");

回答by Anonymous Helper

I don't know if this will work for you, but you can try it out

我不知道这是否适合你,但你可以试试

This one converts <br/>to new line in textarea

这个转换<br/>为 textarea 中的新行

$(this).val().split("<br/>").join("\n");

And this one converts it back

而这个将它转换回来

boxText.split("\n").join("<br/>");

This works for me

这对我有用