Problematic Quotes in Javascript callFunction()

穿精又带淫゛_ 提交于 2019-12-11 14:26:45

问题


I would like to know how to maintain the ability to have both single and double quotes in text that I am passing to a JavaScript function with callFunction()? All three cases below appears to be failing.

Mixing the single and double quotes will work but I would like to be able to use both single and double quotes in my text blocks. It is curious why the browser is evaluating html special characters before passing it to the Javascript function.

Thanks, Robin

<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Untitled Document</title>

<script type="text/javascript">

function callFunction(text){

    alert(text);

}

</script>

</head>

<body>

<!--This will not work due to &#039;-->
<a href="javascript: callFunction('Robin&#039;s Text')">Robin&#039;s Text</a> 

<br />
<br />

<!--And this will not work due to &#034;-->
<a href='javascript: callFunction("Robin&#034;s Text")'>Robin&#034;s Text</a>

<br />
<br />

<!--Trying with a slash but not working either-->
<a href='javascript: callFunction("Robin\'s Text")'>Robin's Text</a>

</body>
</html>

回答1:


Thank you all for your advice. With it, I have found a workable solution. It appears that using both backslash and HTML Special Characters together will allow it to work. I am not sure why both is required?

<!--Using HTML Special Characters (&#039;) alone will not work-->
<a href="#" onClick="callFunction('Robin&#039;s Text')">Robin&#039;s Text</a>

<br />
<br />

<!--Using backslash (\) alone will not work-->
<a href="javascript: callFunction('Robin\"s Text')">Robin"s Text</a>

<br />
<br />

<!--But using a combination of both will work!-->
<a href="javascript: callFunction('Robin\&#034;s Text')">Robin"s Text</a>



回答2:


Assuming that the input for the JS function will be machine-generated, then you should escape the input from the server, then unescape it in the client-side as below:

HTML:

<a href="#" onclick='callFunction("Robin%27s%20Text")'>Robin's Text</a>
<br>
<a href="#" onclick='callFunction("Robin%22s%20Text")'>Robin"s Text</a>

JS:

function callFunction(text){
    alert(decodeURIComponent(text));
}

See the working code at:

JSFiddle



来源:https://stackoverflow.com/questions/23191193/problematic-quotes-in-javascript-callfunction

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