Javascript引文转义错误
我需要将一个按钮打印到一个div,该div将传递一个变量MyVar(string),或者确切地说,它的值,作为一个参数传递给函数addfr()。守则:Javascript引文转义错误,javascript,html,Javascript,Html,我需要将一个按钮打印到一个div,该div将传递一个变量MyVar(string),或者确切地说,它的值,作为一个参数传递给函数addfr()。守则: document.getElementById("somediv").innerHTML="<button onclick=\"addfr(\""+MyVar+"\")\">Add as friend</button>"; document.getElementById(“somediv”).innerHTML=“添加
document.getElementById("somediv").innerHTML="<button onclick=\"addfr(\""+MyVar+"\")\">Add as friend</button>";
document.getElementById(“somediv”).innerHTML=“添加为好友”;
而不是预期的
<button onclick="addfr("MyVar")">Add as friend</button>"
添加为好友”
我得到:
<button onclick="addfr(" MyVar")"="">
这里发生了什么?有没有办法解决这个问题
编辑:对于感兴趣的人,最终解决方案是:
<button onclick=\"addfr(""+MyVar+"")\">Add as friend</button>
添加为好友
它需要HTML转义。请尝试使用“
代替\”
您可以改为使用单引号:
document.getElementById("somediv").innerHTML="<button onclick=\"addfr('"+MyVar+"')\">Add as friend</button>";
document.getElementById(“somediv”).innerHTML=“添加为好友”;
为什么不在字符串中使用单引号而不是双引号(反之亦然)?完全消除了这个问题。不,试过了,问题持续了,这就是我所需要的。它部分解决了问题,尽管我还需要使用\“使其完全工作。