简体   繁体   中英

Set text with \n newline in jQuery

I am appending the following with jQuery.

    game_details_container.append('<div class="game_detail_peg"><table><tr><th class="game_detail_tr"><span class="game_detail_tr_round">'+innings_num+'</span> '+team_home+'</th> </tr><tr><td>'+inningsInfo['innings_pp_h']+'</td></tr></table></div>');

The variable inningsInfo['innings_pp_h'] has text that includes newlines '\n' tokens.

However the text is set so that it flows and does not honor the newline. Is there a way to fix this.

Can anyone give me a point in the right direction on how to fix this?

If what you want is for your \n characters to create line-breaks in the rendered HTML, you can try:

game_details_container.append('<div class="game_detail_peg"><table><tr><th class="game_detail_tr"><span class="game_detail_tr_round">'
    + innings_num
    + '</span> ' 
    + team_home
    + '</th> </tr><tr><td>'
    + inningsInfo['innings_pp_h'].split("\n").join("<br />")
    + '</td></tr></table></div>'
);

HTML ignores newline characters, unless they are inside of a <pre> tag. To force a line-break you need to use <br> , <div> (or any other block-level element), or place your content inside of a <pre> tag.

Rendering of HTML ignores newlines and repeated whitespace, so you need to use markup to achieve the same result with something like:

inningsInfo['innings_pp_h'].replace(/\n/g, '<br/>')

Concatenating strings is a mess. Use a template instead.

var TEMPLATE = '<div class="game_detail_peg"><table><tr><th class="game_detail_tr"><span class="game_detail_tr_round">{{INNINGS_NUM}}</span>{{TEAM_HOME}}</th> </tr><tr><td>{{INNINGSINFO}}</td></tr></table></div>';

var renderedHtml = TEMPLATE.replace(/{{INNINGS_NUM}}/, innings_num)
                           .replace(/{{TEAM_HOME}}/, team_home)
                           .replace(/{{INNINGSINFO}}/, inningsInfo['innings_pp_h'].replace(/\n/g, '<br/>'));

game_details_container.append(renderedHtml);

Much tidier and more understandable.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM