最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

Insert newline into javascript string - Stack Overflow

programmeradmin1浏览0评论

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.

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.

Share Improve this question edited May 23, 2017 at 12:17 CommunityBot 11 silver badge asked May 28, 2013 at 13:31 markymarky 5,06818 gold badges63 silver badges109 bronze badges 0
Add a comment  | 

1 Answer 1

Reset to default 13

If you are output is HTML and you want newlines you have two options:

Either use a <pre> tag as a wrapper to your text (not suitable here I think)

<pre>some Text

with newlines</pre>

or add <br> instead of \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

$('#yourLabel').html( goTosList );
发布评论

评论列表(0)

  1. 暂无评论