javascript 将文本附加到带有换行符的文本区域

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

append text to a textarea with line breaks

javascriptjqueryappendtextarealine-breaks

提问by Afshin

I want to add some strings to a textareawhich are file basenames. Everything is fine, but the only problem is that it mixes all the values and there are not any line breaks:

我想向 a 中添加一些字符串,textarea它们是文件基名。一切都很好,但唯一的问题是它混合了所有值并且没有任何换行符:

var file_name = file.file_name;
var base = new String(file_name).substring(file_name.lastIndexOf('/') + 1); 
if(base.lastIndexOf(".") != -1)       
base = base.substring(0, base.lastIndexOf("."));
$('textarea#image_Basename').append(base).split('\n');

These are my file basenames:

这些是我的文件基名:

5b0cd65710052633dc5dcac406a382c4
212asaddgcvjh622sdsds22113554dfd
5sd5weea55rr6qasfdjkloijhj665s6a

But after storing the data in to the database and retrieving it, the result I get is:

但是在将数据存储到数据库中并检索它之后,我得到的结果是:

5b0cd65710052633dc5dcac406a382c4212asaddgcvjh622sdsds22113554dfd5sd5weea55rr6qasfdjkloijhj665s6a

回答by rink.attendant.6

To preserve newlines that are coming from a database or whatever, replace the newline characters with the HTML entity for a line feed: 


要保留来自数据库或其他内容的换行符,请将换行符替换为换行符的 HTML 实体: 


base = base.replace("\n", '
');
$('#image_Basename').append(base);

If you're trying to append each string with a newline at the end, just concatenate it onto the string:

如果您尝试在每个字符串的末尾附加换行符,只需将其连接到字符串上:

$('#image_Basename').append(base + '
');

Also, you're using split on the textareajQuery element, which doesn't make sense as it is an objectnot a string.

此外,您在textareajQuery 元素上使用 split ,这没有意义,因为它object不是string.

回答by Afshin

My Special thanks to @rink.attendant.6, his second method worked for me :) The answer is:

特别感谢@rink.attendant.6,他的第二种方法对我有用:) 答案是:

$('#image_Basename').append(base + '
');

After adding this, I got all the file basenames in separate lines!

添加此内容后,我将所有文件基名放在单独的行中!