简体   繁体   中英

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.

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM