我正在使用 javascript,我尝试将一个字符串传递给一个函数,就像这样
//example string
var f="a";
//add button that sends the value of f to the function
document.getElementById("mydiv").innerHTML="<input type='button' id='myButton' value='Click here' onclick='gothere("+f+");'> ";
function gothere(a){
alert(a);
}
我从未看到警报,在控制台中我看到a is not defined
(我猜是指 f?)
如果我将 f var
设置为一个数字,那么我会看到警报。
我错过了什么?
提前致谢
编辑
我在想也许是这样
var buttonnode= document.createElement('input');
document.getElementById("mydiv").appendChild(buttonnode);
buttonnode.onclick=gothere(f);
不会因为同样的原因工作吗?
最佳答案
当您的 HTML get 被渲染时,您会得到 onclick='gothere(a);'
,但是实际的 a
变量在这个上下文中不存在,您想要将 f 的值作为字符串传递,因此您需要使用 onclick='gothere(\""+f+"\");'
。注意括号内的额外引号。这将呈现给 onclick='gothere("a");'
从而传递字符串。
当使用数字时,它有效,因为调用 onclick='gothere(5);'
是有效的,因为变量不能命名为 5
,并且它传递了数字。
关于javascript - 无法将字符串传递给函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19506220/