问题
This seems to be one step more complicated than similar posts I've seen:
I created the following line within a js function:
content.push("<input type='button' value='Use This Location' onclick='alert(" + result.location.y + "," + result.location.x + ")'/>");
The result is a button with the following:
onclick="alert(40.7445068,-73.9834671)"
but I want the result to be:
onclick="alert('40.7445068,-73.9834671')"
or..you know..just.. however it would take to make the alert show the text, not just the first number.
How can I reformat the quotes within the original block to make that happen?
thanks!
Answer:
Thanks so much folks! Your input (no put intended) led to a workable solution:
content.push('<input type="button" value="Use This Location" onclick="alert(''+ result.location.y + "," + result.location.x + '')" />');
Since it's javascript within HTML within javascript, I passed the push method as single quotes instead of the original double ones, then I was able to make the html element double quotes and the onclick single. Then I had to use '
instead of "
so I could get a special single quote inserted within the HTML.
Again, thanks very much. All the comments were key in solving / I am grateful!
PS: Sorry for answering through an edit: Apparently I have to wait 7 more hours to officially answer my own question because of my limited reputation.
回答1:
content.push("<input type='button' value='Use This Location' onclick='alert(\"" +
result.location.y + ',' + result.location.x + "\")'/>");
EDIT: Fixed up the code some.
回答2:
You should just be able to add escaped single quotes (e.g. \')
so change
onclick='alert(" + result.location.y + "," + result.location.x + ")'
to
onclick='alert(\'" + result.location.y + "," + result.location.x + "\')'
edit: formatting issues
来源:https://stackoverflow.com/questions/11126603/passing-quotes-to-an-onclick-event-within-an-html-element-within-a-javascript-fu