[英]Set text with \n newline in jQuery
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?谁能给我指出如何解决这个问题的正确方向?
If what you want is for your \n
characters 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. HTML 忽略换行符,除非它们在
<pre>
标记内。 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.要强制换行,您需要使用
<br>
、 <div>
(或任何其他块级元素),或将您的内容放在<pre>
标记内。
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/>')
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.更整洁,更容易理解。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.