问题
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 '-->
<a href="javascript: callFunction('Robin's Text')">Robin's Text</a>
<br />
<br />
<!--And this will not work due to "-->
<a href='javascript: callFunction("Robin"s Text")'>Robin"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 (') alone will not work-->
<a href="#" onClick="callFunction('Robin's Text')">Robin'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\"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