问题
How do I escape double quotes in an event handler in HTML?
For example, how do I properly escape the bar
, which is a string literal, in the following code?
<button onclick="foo("bar")")>Click Me</button>
I can't use single quotes for the attribute value since I'm using XHTML. I could use single quotes for string literals, but I'd like to be consistent.
回答1:
<button onclick="foo("bar");">Click Me</button>
And, you can mix them indeed in XHTML, try this in the W3 validator:
<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>foo</title>
</head>
<body>
<div onclick='bar("foo");'></div>
</body>
</html>
There are some tutorials which said single quotes are not valid, but they are incorrect.
回答2:
XHTML prefers double quotes around the attributes. But you can still use single quotes inside the value. The follow for example is XHTML 1.0 Strict
<button onclick="foo('bar')">Click Me</button>
I would suggest looking into progressive enhancement and moving away from the behavioral attributes.
来源:https://stackoverflow.com/questions/4456963/escaping-double-quotes-in-html-event-handlers