新行插入键不适用于`... \ n` +`...`

时间:2019-05-09 17:46:02

标签: javascript

我有一个想要制造的琴弦。在每个单独的行之间,我想插入一个新的行标签,以确保最后一条消息位于由\ n分隔的三个单独的行中。这就是我到目前为止的内容。

confirmationMessage = `This action will assign <strong>${stack.name}</strong> to you. \n\n` + 
                      `<strong>IMPORTANT</strong>: This App is currently owned by ${stack.owner.username} and cannot be reassigned to this owner once this action is executed. \n\n` + 
                      `Are you sure you want to take ownership o fthis Dashboard. \n`;

我有\ n \ n,但它们仍在一行中呈现

1 个答案:

答案 0 :(得分:3)

最可能是因为您将字符串传递给解析器/运行时,而该代码毫无意义。

  • HTML解析器知道如何解析HTML,但不是JavaScript。
  • JavaScript运行时知道如何处理JavaScript,但不知道HTML。

现在,要清楚一点,无论字符串在何处结束,它都将包含换行符,因为您已使用处理为JavaScript的语句来建立了换行符。

如果包含新行字符的字符串最终被JavaScript运行时处理,那么这些字符将被正确处理,但是任何HTML都将变得无意义,并且像其他任何字符串一样被对待:

alert("The line\nbreak escape codes\nwork here.\nBut, <strong>HTML</strong> doesn't.");

但是,如果将包含换行符的字符串发送到HTML解析器,则新行将被视为HTML中的任何换行符,它将被忽略,但会处理HTML。

document.write("The line\nbreak escape codes\nwon't work here.\nBut, <br><strong>HTML</strong> does.");
<div>
You
don't
see
each
word
on
its
own
line
here
because
new
lines
in
HTML
are ignored.
</div>