passing quotes to an onclick event within an html element within a javascript function

自古美人都是妖i 提交于 2021-02-07 09:01:02

问题


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(&#39;'+ result.location.y + "," + result.location.x + '&#39;)" />');

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 &#39; instead of &#34 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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!