我想传递一个参数(即字符串)到Onclick函数。
目前,我是这样做的:
'<input type="button" onClick="gotoNode(' + result.name + ')" />'
例如,result.name = string "Add"。
当我点击这个按钮时,我有一个错误,说“Add is not defined”。由于这个函数调用可以很好地处理数值形参,所以我假设它与字符串中的符号“”有关。
我该如何解决这个问题?
我想传递一个参数(即字符串)到Onclick函数。
目前,我是这样做的:
'<input type="button" onClick="gotoNode(' + result.name + ')" />'
例如,result.name = string "Add"。
当我点击这个按钮时,我有一个错误,说“Add is not defined”。由于这个函数调用可以很好地处理数值形参,所以我假设它与字符串中的符号“”有关。
我该如何解决这个问题?
当前回答
<!---- script ---->
<script>
function myFunction(x) {
document.getElementById("demo").style.backgroundColor = x;
}
</script>
<!---- source ---->
<p id="demo" style="width:20px;height:20px;border:1px solid #ccc"></p>
<!---- buttons & function call ---->
<a onClick="myFunction('red')" />RED</a>
<a onClick="myFunction('blue')" />BLUE</a>
<a onClick="myFunction('black')" />BLACK</a>
其他回答
这是我的工作:
$(element).attr("onClick", 'functionName(' + "\"" + Object.attribute + "\"" + ')');
只需在()中添加\斜杠
※多参数示例
"functionName(" + "'" + parameter1 + "','" + parameter2 + "','" + parameter3 + "','" + parameter4 + "','" + parameter5 + "','" + parameter6 + "')"
多个参数:
bounds.extend(marker.position);
bindInfoWindow(marker, map, infowindow,
'<b>' + response[i].driver_name + '</b><br>' +
'<b>' + moment(response[i].updated_at).fromNow() + '</b>
<button onclick="myFunction(\'' + response[i].id + '\',\'' + driversList + '\')">Click me</button>'
);
如果要求在HTML代码中引用全局对象(JavaScript),您可以尝试这样做。[不要在变量周围使用任何引号('或")]
小提琴参考。
JavaScript:
var result = {name: 'hello'};
function gotoNode(name) {
alert(name);
}
HTML:
<input value="Hello" type="button" onClick="gotoNode(result.name)" />
<!---- script ---->
<script>
function myFunction(x) {
document.getElementById("demo").style.backgroundColor = x;
}
</script>
<!---- source ---->
<p id="demo" style="width:20px;height:20px;border:1px solid #ccc"></p>
<!---- buttons & function call ---->
<a onClick="myFunction('red')" />RED</a>
<a onClick="myFunction('blue')" />BLUE</a>
<a onClick="myFunction('black')" />BLACK</a>
您可以传递一个引用或字符串值。只需将函数放在双逗号“”中,如下所示: