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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-27 06:00:59  来源:igfitidea点击:

Insert newline into javascript string

javascriptinsertnewline

提问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 \rand just \nand 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 );