我想传递一个参数(即字符串)到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”。由于这个函数调用可以很好地处理数值形参,所以我假设它与字符串中的符号“”有关。
我该如何解决这个问题?
当前回答
如果用于生成一组具有不同处理程序参数的按钮。
JavaScript闭包
let some_button = document.createElement( "button" );
some_button.type = "button";
some_button.onclick = doWithParam( some_param );
function doWithParam( param ){
return function(){
alert( param ); // <-- Your code here
}
}
如果我们这样做:
some_button.onclick = foo( some_param );
function foo( param ){
alert( param );
}
然后函数foo在每个更新页面之后启动。
如果我们这样做:
for( let i = 0; i < 10; ++i ){
var inputElement = document.createElement('input');
inputElement.type = "button"
inputElement.addEventListener('click', function(){
gotoNode(result.name);
});
document.body.appendChild(inputElement);
}
然后,对于循环中创建的所有按钮,参数的最后一个值是“result.name”。
其他回答
这是一种发送值或对象的好方法。
<!DOCTYPE html>
<html>
<body>
<h1 onclick="test('wow',this)">Click on this text!</h1>
<script>
var test = function(value,object) {
object.innerHTML= value;
};
</script>
</body>
</html>
这是我的工作:
$(element).attr("onClick", 'functionName(' + "\"" + Object.attribute + "\"" + ')');
只需在()中添加\斜杠
※多参数示例
"functionName(" + "'" + parameter1 + "','" + parameter2 + "','" + parameter3 + "','" + parameter4 + "','" + parameter5 + "','" + parameter6 + "')"
你也可以在字符串中使用重音符号(')
Try:
`<input type="button" onClick="gotoNode('${result.name}')" />`
欲了解更多信息,请访问MDN和Stack Overflow。
由Chrome, Edge, Firefox (Gecko), Opera, Safari支持,但不支持Internet Explorer。
如果你的按钮是动态生成的:
你可以将字符串参数传递给JavaScript函数,如下所示:
我传递了三个参数,第三个是字符串参数。
var btn ="<input type='button' onclick='RoomIsReadyFunc("+ID+","+RefId+",\""+YourString+"\");' value='Room is Ready' />";
// Your JavaScript function
function RoomIsReadyFunc(ID, RefId, YourString)
{
alert(ID);
alert(RefId);
alert(YourString);
}
多个参数:
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>'
);