我在 asp.net 上的代码隐藏中使用的 javascript 有问题,经过几个小时的研究后发现是转义字符的问题。
起初我用这个。
ScriptManager.RegisterStartupScript(this, this.GetType(), "temp", "alert('Can't delete this data because it is bound with rate plan');", true);
这会导致 javascript 错误,因为“can't”处的引号需要使用转义字符,所以我使用了。
ScriptManager.RegisterStartupScript(this, this.GetType(), "temp", "alert('Can\'t delete this data because it is bound with rate plan');", true);
但还是不行。
我终于用上了
ScriptManager.RegisterStartupScript(this, this.GetType(), "temp", "alert('Can\\'t delete this data because it is bound with rate plan');", true);
很好。
我很好奇为什么我们需要使用 \\'
而不是 \'
来使转义字符正常工作。
最佳答案
\
是 C# 和 JavaScript 中的转义字符。
当您给 C# "\'"
时,会创建一个包含撇号的字符串。
当你给 C# "\\'"
然后第一个 \
转义第二个 \
(所以第二个 \
不被视为转义字符)并且 '
被视为普通 '
(因为字符串没有用 '
分隔) >.
关于c# - 为什么在字符串中使用引号的javascript转义字符需要\\' instead of\',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5855670/