[英]Escaping double quotes around argument of onClick in single quote string
I'm asking about escaping such string: 我问的是转义这样的字符串:
function my(mstr){alert(mstr);};
document.getElementById('home').innerHTML = '<button onclick="my("a")">a</button>'
We have 我们有
'<... onclick="fun("a")"...>'
so its double quotes inside of double quotes inside of single quotes. 因此其双引号位于单引号内的双引号内。
Simple '<button onclick="my(\\"a\\")">...'
gives syntax error. 简单的
'<button onclick="my(\\"a\\")">...'
给出语法错误。
I know that i could escape it like 我知道我可以逃脱
'<button onclick="my(\\'a\\')">...'
but i wonder why this syntax error appears. 但我想知道为什么出现此语法错误。
EDIT: here's jsfiddle for it http://jsfiddle.net/pVy9W/1/ 编辑:这是它的jsfiddle http://jsfiddle.net/pVy9W/1/
EDIT2: BallBin said it renders <button onclick="my("a")">a</button>
so EDIT2:BallBin说它呈现
<button onclick="my("a")">a</button>
trying to escape backslash: 试图逃避反斜杠:
'<button type="button" onclick="my(\\\\\\"a\\\\\\")">a</button>';
it renders as strange: 它呈现为奇怪:
<button type="button" onclick="my(\\" a\\")"="">a</button>
and gives error: 并给出错误:
Uncaught SyntaxError: Unexpected token ILLEGAL
Double quotes inside HTML attribute values that are delimited by double quotes should be represented as "
用双引号分隔的HTML属性值中的双引号应表示为
"
The \\
character has no special significance in HTML. \\
字符在HTML中没有特殊意义。
Your JavaScript string is delimited with '
characters so "
do not need escaping (with \\
) for JavaScript. 您的JavaScript字符串用
'
字符分隔,因此"
不需要对JavaScript进行转义(使用\\
)。
I'd avoid nesting JS inside HTML inside JS in the first place though. 我首先要避免将JS嵌套在JS内的HTML内。 Use DOM instead of string manipulation.
使用DOM而不是字符串操作。
// Create button with content and an event handler
var button = document.createElement('button');
button.appendChild(document.createTextNode('a'));
button.addEventListener("click", clickHandler);
// Get container, empty it and add the button to it
var container = document.getElementById('home');
container.innerHTML = ''; // Delete all nodes inside the element
container.appendChild(button);
function clickHandler(event) {
my("a");
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.