7

I have read this question/answer and 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.

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.

4

1 回答 1

13

如果你的输出是 HTML 并且你想要换行符,你有两个选择:

使用<pre>标签作为文本的包装(我认为不适合这里)

<pre>some Text

with newlines</pre>

或添加<br>而不是\n\r

some Text<br>with newlines

所以在你的代码中,这将转化为

goTosList += (element['name'] === undefined ? '' : element['name']) + '<br>';

稍后将其插入到 DOM 中

$('#yourLabel').html( goTosList );
于 2013-05-28T13:34:53.310 回答