javascript 警报弹出窗口中的换行符

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/12603700/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-26 16:38:20  来源:igfitidea点击:

line break in alert popup

c#javascriptasp.net

提问by nav100

I am trying to add a new line Javascript alert message. I tried '\n' and 'Environment.NewLine'. I am getting Unterminated string constant error. Could you please let me know what could be the problem? I appreciate any help. I also tried \r\n.

我正在尝试添加一个新行 Javascript 警报消息。我试过 '\n' 和 'Environment.NewLine'。我收到未终止的字符串常量错误。你能告诉我可能是什么问题吗?我很感激任何帮助。我也试过\r\n。

string msg = "Your session will expire in 10 minutes. \n Please save your work to avoid this.";


if (!this.ClientScript.IsStartupScriptRegistered(ID)) 
   this.ClientScript.RegisterStartupScript(GetType(), ID, String.Format("<script language=JavaScript>setTimeout(\'alert(\"{1}\");\',{0}*1000);</script>", sTime, msg));

回答by Tim B James

I would suspect that you need to change your code to;

我怀疑您需要将代码更改为;

string msg = "Your session will expire in 10 minutes. \n Please save your work to avoid this.";

And escape the \notherwise your code outputted would actually include the line break rather than \n

并转义\n否则您输出的代码实际上将包含换行符而不是\n

Your output code would look like:

您的输出代码如下所示:

setTimeout('alert("Your Session....
 Please save your work to ....");', 1000);

Rather than:

而不是:

setTimeout('alert("Your Session....\n Please save your work to ....");', 1000);

回答by Hunter-974

I'm not sure, but I think that \n is escaped in the string.Format method, like \". Maybe you should use \\n instead.

我不确定,但我认为 \n 在 string.Format 方法中被转义,比如 \"。也许你应该使用 \\n 代替。

Edited : and the first \ of \\n has been escaped when i posted that. xD

编辑:当我发布时,\\n 的第一个 \ 已被转义。xD

回答by Joel Etherton

At first glance I would say the primary problem is that you're escaping the 'character around your alert. Since your string is defined by the double quotes, you don't need to escape this character.

乍一看,我会说主要问题是您正在逃避'警报周围的角色。由于您的字符串是由双引号定义的,因此您无需转义此字符。

回答by m4ngl3r

Adding a @at the beginning should help.

@在开头添加 a应该会有所帮助。

回答by Losbear

add "@" at the beginning of your string - like this:

在字符串的开头添加“@” - 像这样:

string msg = @"Your session ....";

回答by Marc B

The code looks fine, so I'm going to guess that you're using a message that itself has a 'quote in it, causing the JS syntax error. For inserting dynamic text into a Javascript code block, you really should use JSON to make your C# strings 'safe' for use in JS.

代码看起来不错,所以我猜你正在使用一个本身有'引号的消息,导致 JS 语法错误。为了将动态文本插入到 Javascript 代码块中,您确实应该使用 JSON 使您的 C# 字符串在 JS 中“安全”使用。

Consider JSON the go-to method for preventing the JS equivalent of SQL injection attacks.

将 JSON 视为防止 JS 等效 SQL 注入攻击的首选方法。