我想传递一个参数(即字符串)到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”。由于这个函数调用可以很好地处理数值形参,所以我假设它与字符串中的符号“”有关。
我该如何解决这个问题?
当前回答
如果要求在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>
<button style="background-color: gray;color:white;" onclick="displayAlert('the message')">alert</button>
<script>
function displayAlert(msg){
alert(msg);
}
</script>
我建议甚至不要使用HTML的onclick处理程序,而使用一些更常见的东西,如document.getElementById。
HTML:
<input type="button" id="nodeGoto" />
JavaScript:
document.getElementById("nodeGoto").addEventListener("click", function() {
gotoNode(result.name);
}, false);
多个参数:
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>'
);
要传递多个参数,可以通过将字符串与ASCII值连接来强制转换。比如,对于单引号,我们可以使用'
var str = "'" + str + "'";
可以传递给onclick()事件的相同参数。在大多数情况下,它适用于所有浏览器。