Should &'s be escaped in onclick=“…”?

2019-07-17 16:08发布

问题:

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

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

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>

Thanks!

回答1:

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

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).

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.



回答2:

It's valid to leave unescaped & in your attributes if the following characters don't complete some HTML entity. See:

var test = ab&lt;

This will be broken without escaping & as &amp; (see this fiddle). So, if you're in full control of your code and you're sure that no HTML entity will appear in it, you shouldn't escape &. It will make you code cleaner. But if there is a chance that some HTML entity may appear here and broke everything, you have to escape &.