javascript 在 jQuery 中使用 \n 换行符设置文本

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/6717711/
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-25 21:38:06  来源:igfitidea点击:

Set text with \n newline in jQuery

javascriptjqueryhtml

提问by Chin

I am appending the following with jQuery.

我正在用 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.

变量 inningsInfo['innings_pp_h'] 的文本包含换行符 '\n' 标记。

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?

谁能给我一个关于如何解决这个问题的正确方向的观点?

回答by aroth

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

如果您想要的是让您的\n角色在呈现的 HTML 中创建换行符,您可以尝试:

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.

HTML 会忽略换行符,除非它们在<pre>标签内。要强制换行,您需要使用<br>, <div>(或任何其他块级元素),或将您的内容放在<pre>标签内。

回答by Brian Hogg

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

HTML 的呈现会忽略换行符和重复的空格,因此您需要使用标记来实现相同的结果,例如:

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

回答by Mark Holland

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.

更整洁,更容易理解。