javascript 在javascript字符串中插入换行符
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/16793420/
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
Insert newline into javascript string
提问by marky
I have read this question/answerand this one, but I can't get it to work in my situation.
我看了这个提问/回答和这一个,但我不能得到它的工作在我的处境。
I'm building a list of names from a json array returned from a php script. After the below code I'm putting the goTosList string into a label via jquery. I need each name to be on a new line.
我正在从 php 脚本返回的 json 数组中构建名称列表。在下面的代码之后,我通过 jquery 将 goTosList 字符串放入标签中。我需要每个名字都在一个新行上。
The below code is just outputting
下面的代码只是输出
var goTosList = '';
if (data !== 'empty') {
// Build the go tos list as a comma-separated string
$.each(data, function(index,element) {
goTosList += (element['name'] === undefined ? '' : element['name']) + '\n\r';
});
}
I've tried just \r
and just \n
and without the single quotes. I can't get it to work.
我试过只是\r
和\n
没有单引号。我无法让它工作。
回答by Sirko
If you are output is HTML and you want newlines you have two options:
如果你的输出是 HTML 并且你想要换行,你有两个选择:
Either use a <pre>
tag as a wrapper to your text (not suitable here I think)
要么使用<pre>
标签作为文本的包装器(我认为不适合这里)
<pre>some Text
with newlines</pre>
or add <br>
instead of \n\r
:
或添加<br>
而不是\n\r
:
some Text<br>with newlines
So in your code this would translate to
所以在你的代码中,这将转化为
goTosList += (element['name'] === undefined ? '' : element['name']) + '<br>';
and later on insert this into the DOM by
然后通过以下方式将其插入到 DOM 中
$('#yourLabel').html( goTosList );