我想传递一个参数(即字符串)到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”。由于这个函数调用可以很好地处理数值形参,所以我假设它与字符串中的符号“”有关。
我该如何解决这个问题?
当前回答
<button style="background-color: gray;color:white;" onclick="displayAlert('the message')">alert</button>
<script>
function displayAlert(msg){
alert(msg);
}
</script>
其他回答
这是我的工作:
$(element).attr("onClick", 'functionName(' + "\"" + Object.attribute + "\"" + ')');
只需在()中添加\斜杠
※多参数示例
"functionName(" + "'" + parameter1 + "','" + parameter2 + "','" + parameter3 + "','" + parameter4 + "','" + parameter5 + "','" + parameter6 + "')"
如果要求在HTML代码中引用全局对象(JavaScript),您可以尝试这样做。[不要在变量周围使用任何引号('或")]
小提琴参考。
JavaScript:
var result = {name: 'hello'};
function gotoNode(name) {
alert(name);
}
HTML:
<input value="Hello" type="button" onClick="gotoNode(result.name)" />
<button style="background-color: gray;color:white;" onclick="displayAlert('the message')">alert</button>
<script>
function displayAlert(msg){
alert(msg);
}
</script>
多个参数:
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:
<button id="a1" type="button" onclick="return a1_onclick('a1')">a1</button>
JavaScript:
<script language="javascript" type="text/javascript">
function a1_onclick(id) {
document.getElementById(id).style.backgroundColor = "#F00";
}
</script>
注意:在HTML代码中,请确保在('a1')等符号之间发送参数