javascript - Escaping double quotes around argument of onClick in single quote string -
i'm asking escaping such string:
function my(mstr){alert(mstr);}; document.getelementbyid('home').innerhtml = '<button onclick="my("a")">a</button>'
we have '<... onclick="fun("a")"...>'
double quotes inside of double quotes inside of single quotes.
simple '<button onclick="my(\"a\")">...'
gives syntax error.
know escape
'<button onclick="my(\'a\')">...'
but wonder why syntax error appears.
edit: here's jsfiddle http://jsfiddle.net/pvy9w/1/
edit2: ballbin said renders <button onclick="my("a")">a</button>
trying escape backslash:
'<button type="button" onclick="my(\\\"a\\\")">a</button>';
renders strange:
<button type="button" onclick="my(\" a\")"="">a</button>
, gives error:
uncaught syntaxerror: unexpected token illegal
double quotes inside html attribute values delimited double quotes should represented "
\
character has no special significance in html.
your javascript string delimited '
characters "
not need escaping (with \
) javascript.
i'd avoid nesting js inside html inside js in first place though. use dom instead of string manipulation.
// create button content , event handler var button = document.createelement('button'); button.appendchild(document.createtextnode('a')); button.addeventlistener("click", clickhandler); // container, empty , add button var container = document.getelementbyid('home'); container.innerhtml = ''; // delete nodes inside element container.appendchild(button); function clickhandler(event) { my("a"); }
Comments
Post a Comment