Reputation: 5699
I'm struggling with a complex nested quotes statement here :
var name = "foo";
$("#list").append("<li data-theme='c'><a href='#details' onclick='sessionStorage.name=PRINT_VAR_NAME_HERE;' data-transition='slide'>PRINT_VAR_NAME_HERE</a></li>");
I am able to print the variable's value fine in the second position by using : "+name+"
But not sure how to get it done in the first position.
(I have used 'PRINT_VAR_NAME_HERE' as a placeholder for the first and second positions)
Any ideas ? Thanks.
Upvotes: 1
Views: 7645
Reputation: 157
I was running into the same issue of trying to figure out how to nest quotes in a javaScript in order to generate HTML. I was hitting a particular snag in the 'onclick' area because I was including a variable within it. In addition, the browser was interpreting my quotes incorrectly.
The solution: You have to explicitly tell the browser which quotes you ARE using and where. And you do this by using ' for single-quote, and " for double-quotes.
Hopefully this is helpful to someone...
document.getElementById("item-controls-" + id).innerHTML = "<span class=\'controls\' id=\'save-control\' onclick='saveForm(\"" + id + "\")'>save</span> ...
Upvotes: 0
Reputation: 253308
Just use the string-delimiters (the "
) to break the string and concatenate the string with your variable, and escape (with the backslash) any quotes that you need to appear in the string itself:
$("#list")
.append("<li data-theme='c'><a href='#details' onclick='sessionStorage.name=\"" + name + "\"' data-transition='slide'>"+ name + "</a></li>");
I am, of course, assuming that you want to quote the variable in the string, otherwise I couldn't see what the problem would be.
Upvotes: 2