是否应在onclick ="..."中对&进行转义? [英] Should &'s be escaped in onclick="..."?

查看:88
本文介绍了是否应在onclick ="..."中对&进行转义?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我还没有找到合适的答案:

I haven't found a proper answer for this yet:

应& (和号)在onclick="..."中转义? (或者,是在每个HTML属性中?)

Should & (ampersand) be escaped in onclick="..."? (Or for that matter, in every HTML attribute?)

我尝试在jsFiddle和W3C的验证器上运行转义和未转义的测试,都可以正常工作...

I have tried running both escaped and unescaped tests on jsFiddle and W3C's validator, both are working...

http://jsfiddle.net/6LuES

<div onclick="if (1==1 && 2==2) alert('hello there');">Without escape</div>
<div onclick="if (1==1 &amp;&amp; 2==2) alert(&#39;hello there&#39;);">With escape</div>


http://validator.w3.org/#validate_by_input

<!DOCTYPE html>
<html lang="en"><head><meta charset="utf-8"><title></title></head><body>

<div onclick="if (1==1 && 2==2) alert('hello there');">Click me</div><br>
<div onclick="if (1==1 &amp;&amp; 2==2) alert(&#39;hello there&#39;);">Click me</div>

</body></html>

谢谢!

推荐答案

在任何HTML版本中,代表与号字符&"始终是正确的在属性值中使用引用&amp;.

It is always correct, in any HTML version, to represent the ampersand character "&" using the reference &amp; within an attribute value.

使用它是否正确还取决于上下文和HTML版本.在任何形式的XHTML中,它都是永远不正确的.在其他形式中,它基本上取决于下一个字符的类型,但是(如果它是名称字符)还取决于HTML版本和属性的性质(对URL值属性的处理不同).

Whether it is also correct to use it as such depends on context and on HTML version. In any flavor of XHTML, it is never correct. In other flavors, it depends, basically on the kind of the next character, but – if it is a name character – also on HTML version and the nature of the attribute (URL values attributes are treated differently).

简而言之,您应该在有疑问时将其转义,并且通常应避免在属性中使用任何复杂的JavaScript代码.在属性值内使用函数调用是可以的,但是任何更复杂的操作都容易引起混乱.实际上,出于充分的原因,许多人都喜欢将所有JavaScript代码放入外部JavaScript文件中.作为副作用,可以避免这样的问题-由将JavaScript嵌入HTML引起.

The short story is that you should escape it when in doubt, and normally avoid any complicated JavaScript code in attributes. Using a function call inside an attribute value is OK, but anything more complicated easily leads into confusion. In fact, many people favor putting all JavaScript code into external JavaScript files, for good reasons; as a side effect, thet avoid problems like this – caused by embedding JavaScript into HTML.

这篇关于是否应在onclick ="..."中对&amp;进行转义?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆