Escaping Double Quotes in HTML Event Handlers

穿精又带淫゛_ 提交于 2020-01-15 12:47:08

问题


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(&quot;bar&quot;);">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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!