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


当前回答

JavaScript中的特殊字符代码列表:

Code    Outputs
\'  single quote
\"  double quote
\\  backslash
\n  new line
\r  carriage return
\t  tab
\b  backspace
\f  form feed

其他回答

我使用了:"\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表示新行

alert("Welcome\nto Jumanji");

警报(“欢迎\ nto Jumanji);

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

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