Escaping double quotes around argument of onClick

2019-06-05 23:58发布

问题:

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.

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/

EDIT2: BallBin said it renders <button onclick="my("a")">a</button> so
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

回答1:

Double quotes inside HTML attribute values that are delimited by double quotes should be represented as &quot; The \ character has no special significance in HTML.

Your JavaScript string is delimited with ' characters so " do not need escaping (with \) for JavaScript.


I'd avoid nesting JS inside HTML inside JS in the first place though. Use DOM instead of string manipulation.

// 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");
}