如何在JavaScript警告框中添加新行?


当前回答

Alert ("some text\nmore text in a new line");

输出:

一些文本 新行中有更多文本

其他回答

我使用了:"\n\r" -它只能在双引号中使用。

var fvalue = "foo";
var svalue = "bar";
alert("My first value is: " + fvalue + "\n\rMy second value is: " + svalue);

will alert as:

My first value is: foo
My second value is: bar

我看到有些人在MVC中遇到了问题,所以……使用模型传递“\n”的一个简单方法是使用HTML,在我的情况下甚至使用翻译文本。Raw来插入文本。这为我解决了问题。在下面的代码中,Model。警报可以包含换行符,如“Hello\nWorld”…

alert("@Html.Raw(Model.Alert)");
alert("text\nnew Line Text");

文档:Window.alert ()


Firefox:

铬:

优势:

\n将不会工作,如果你在Java代码中:

<% System.out.print("<script>alert('Some \n text')</script>"); %>

我知道这不是答案,只是觉得这很重要。

只是为了帮助任何人,当从c#代码后面这样做时,我必须使用双转义字符,否则我会得到一个“未终止字符串常量”JavaScript错误:

ScriptManager.RegisterStartupScript(this, this.GetType(), "scriptName", "alert(\"Line 1.\\n\\nLine 2.\");", true);