jQuery 在 onclick 事件中传递参数时转义撇号
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2846044/
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
Escape apostrophe when passing parameter in onclick event
提问by RememberME
I'm passing the company name to an onclick event. Some company names have apostrophes in them. I added '.Replace("'", "'")' to the company_name field. This allows the onclick event to fire, but the confirm message displays as "Jane&# 39;s Welding Company".
我将公司名称传递给 onclick 事件。一些公司名称中带有撇号。我在 company_name 字段中添加了 '.Replace("'", "'")'。这允许触发 onclick 事件,但确认消息显示为“Jane's Welding Company”。
<a href="#" onclick="return Actionclick('<%= Url.Action("Activate", new {id = item.company_id}) %>', '<%= Html.Encode(item.company1.company_name.Replace("'", "'")) %>');" class="fg-button fg-button-icon-solo ui-state-default ui-corner-all"><span class="ui-icon ui-icon-refresh"></span></a>
<script type="text/javascript">
function Actionclick(url, companyName)
{
if (confirm('This action will activate this company\'s primary company ('+companyName+') and all of its other subsidiaries. Continue?'))
{
location.href = url;
};
};
EDITThe confirm message shows the &# 39; in the message rather than the '. When I typed it out here, it replaced the &# 39; with a '. Added spaces so that wouldn't happen. I want to know the best way to pass it to my onclick event and also properly display it in the message without doing multiple replaces (if there is a better way).
编辑确认消息显示 39; 在消息中而不是 '. 当我在这里输入时,它取代了 39; 带有 '. 添加了空格,以免发生这种情况。我想知道将它传递给我的 onclick 事件的最佳方法,并在消息中正确显示它而不进行多次替换(如果有更好的方法)。
回答by Brenton Alker
There are two options as I see it.
在我看来,有两种选择。
If you wrap the parameters in quotes (") instead of apostrophes/single quotes (') then you shouldn't need to escape it at all. HTML encoding will take care of encoding any quotes (if they are in the string) and the apostrophe's won't be a problem. Though, as the javascript is already wrapped in quotes, you will need to backslash escape your quotes. eg:
onclick="return Actionclick(\"<%= Url.Action("Activate", new {id = item.company_id}) %>\", \"<%= Html.Encode(item.company1.company_name) %>\");"
Backslash escape the company name as it's only the final javascript string that needs the apostrophe escaped, not the HTML. eg:
onclick="return Actionclick('<%= Url.Action("Activate", new {id = item.company_id}) %>', '<%= Html.Encode(item.company1.company_name.Replace("'", "\\'")) %>');"
如果您将参数用引号 (") 而不是撇号/单引号 (') 括起来,那么您根本不需要转义它。HTML 编码将负责编码任何引号(如果它们在字符串中)和撇号不会有问题。不过,由于 javascript 已经包含在引号中,因此您需要使用反斜杠来转义引号。例如:
onclick="return Actionclick(\"<%= Url.Action("Activate", new {id = item.company_id}) %>\", \"<%= Html.Encode(item.company1.company_name) %>\");"
反斜杠转义公司名称,因为它只是需要转义撇号的最终 javascript 字符串,而不是 HTML。例如:
onclick="return Actionclick('<%= Url.Action("Activate", new {id = item.company_id}) %>', '<%= Html.Encode(item.company1.company_name.Replace("'", "\\'")) %>');"
回答by bobince
You've got a JavaScript string literal inside an HTML attribute value.
您在 HTML 属性值中有一个 JavaScript 字符串文字。
So you would need to first JS-encode the value (replacing the '
with \'
and \
with \\
), thenHTML-encode. Currently you are HTML-encoding the '
(which would be ineffective, since the browser would decode it back to an apostrophe before the JS engine saw it)... and then HTML-encoding it again, leaving it literally meaning '
.
因此,您需要首先对值进行 JS 编码(替换'
with\'
和\
with \\
),然后进行HTML 编码。目前,您正在对'
( 这将是无效的,因为浏览器会在 JS 引擎看到它之前将其解码回撇号) 进行 HTML 编码……然后再次对其进行 HTML 编码,使其字面意思是'
.
Use a JSON encoder to turn a string (or any other value type) into a JavaScript literal.
使用 JSON 编码器将字符串(或任何其他值类型)转换为 JavaScript 文字。
However. Writing JavaScript in a string utterly sucks. Keeping track of multiple layers of escaping isn't something the mind is good at. So don't do it. Avoid inline event handler attributes at all times. Instead, use static script and assign handlers from JavaScript itself, using unobtrusive scripting.
然而。在字符串中编写 JavaScript 非常糟糕。跟踪多层逃逸并不是大脑所擅长的。所以不要这样做。始终避免内联事件处理程序属性。相反,使用静态脚本并从 JavaScript 本身分配处理程序,使用不显眼的脚本。
<a class="dangerous fg-button fg-button-icon-solo ui-state-default ui-corner-all"
href="<%= Server.HTMLEncode(Url.Action("Activate", new {id = item.company_id})) %>"
title="This action will activate this company's primary company (<%= Server.HTMLEncode(companyName) %>) and all of its other subsidiaries."
>
<span class="ui-icon ui-icon-refresh"></span>
</a>
(I'll use jQuery since you have it in your tags:)
(我将使用 jQuery,因为您的标签中有它:)
<script type="text/javascript">
$('.dangerous').click(function() {
return confirm(this.title+' Continue?');
});
</script>
However note that this is an abuse of <a>
. Actions that make an active change to something should never be sent, or be allowed to be received, as a GET request. You should instead use a button that submits a POST request (either directly as a form, or via AJAX). (You should also consider using ASP.NET's built-in controls instead of templating the values in, to avoid having to call HTMLEncode
quite so much.)
但是请注意,这是对<a>
. 对某些内容进行主动更改的操作不应作为 GET 请求发送或允许接收。您应该改为使用提交 POST 请求的按钮(直接作为表单,或通过 AJAX)。(您还应该考虑使用 ASP.NET 的内置控件而不是模板化其中的值,以避免调用HTMLEncode
太多。)
See this classic WTFfor one way in which this can bite you.
查看这个经典的 WTF,了解它可以咬你的一种方式。
回答by Atalie
I just encountered this 5 years later so I'll share what worked for me.
5 年后我才遇到这个问题,所以我将分享对我有用的方法。
Check out HttpUtility.JavaScriptStringEncodeon MSDN
在 MSDN 上查看HttpUtility.JavaScriptStringEncode
You can use this to encode the string on the server side when setting the property's value. This will produce the unicode representation of the apostrophe - "\u0027" which can be passed in to the JavaScript onclick.
您可以在设置属性值时使用它在服务器端对字符串进行编码。这将生成撇号的 unicode 表示 - “\u0027”,它可以传递给 JavaScript onclick。
For the original example:
对于原始示例:
item.company1.company_name = HttpUtility.JavaScriptStringEncode("Jane's Welding Company");
will become
会变成
"Jane'\u0027s Welding Company"
A note on HttpUtility.JavaScriptStringEncode - You can choose to specify a boolean to encode the string with double quotation marks (bool addDoubleQuotes). However, since this string will be used as a parameter to a JavaScript function, you do not want the extra quotes.
关于 HttpUtility.JavaScriptStringEncode 的说明 - 您可以选择指定一个布尔值来使用双引号 (bool addDoubleQuotes) 对字符串进行编码。但是,由于此字符串将用作 JavaScript 函数的参数,因此您不需要额外的引号。