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


当前回答

警报('交易已被批准。\ nThank你);

只需添加一个换行符\n。

alert('The transaction has been approved.\nThank you');
//                                       ^^

其他回答

当你想用javascript写一个php变量的alert时,你必须在“\n”之前加一个“\”。 相反,弹出的警告不起作用。

ex:

PHP :
$text = "Example Text : \n"
$text2 = "Example Text : \\n"

JS:
window.alert('<?php echo $text; ?>');  // not working
window.alert('<?php echo $text2; ?>');  // is working

你可以用\n表示新行

alert("Welcome\nto Jumanji");

警报(“欢迎\ nto Jumanji);

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

alert("@Html.Raw(Model.Alert)");

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

输出:

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

你必须使用双引号来显示特殊字符,如\n \t等…在js中的警告框 例如在PHP脚本中:

$string = 'Hello everybody \n this is an alert box';
echo "<script>alert(\"$string\")</script>";

但是,当您希望显示以双引号指定的字符串时,可能会出现第二个问题。

参见链接文本

如果字符串用双引号(")括起来,PHP将为特殊字符解释更多转义序列

转义序列\n被转换为0x0A ASCII转义字符,该字符不会显示在警告框中。解决方案包括转义这个特殊的序列:

$s = "Hello everybody \\n this is an alert box";
echo "<script>alert(\"$string\")</script>";

如果您不知道字符串是如何封装的,则必须将特殊字符转换为它们的转义序列

$patterns = array("/\\\\/", '/\n/', '/\r/', '/\t/', '/\v/', '/\f/');
$replacements = array('\\\\\\', '\n', '\r', '\t', '\v', '\f');
$string = preg_replace($patterns, $replacements, $string);
echo "<script>alert(\"$string\")</script>";