我想传递一个参数(即字符串)到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的onclick处理程序,而使用一些更常见的东西,如document.getElementById。
HTML:
<input type="button" id="nodeGoto" />
JavaScript:
document.getElementById("nodeGoto").addEventListener("click", function() {
gotoNode(result.name);
}, false);
其他回答
你也可以在字符串中使用重音符号(')
Try:
`<input type="button" onClick="gotoNode('${result.name}')" />`
欲了解更多信息,请访问MDN和Stack Overflow。
由Chrome, Edge, Firefox (Gecko), Opera, Safari支持,但不支持Internet Explorer。
如果您正在动态添加按钮或链接,并面临这个问题,那么这可能会有所帮助。我是这样解决的:
var link= $(contentData1[i]).find("td:first font b a").attr("href",'javascript:onClick=openWin(\'' + tdText + '\')');
我是新的HTML, jQuery和JavaScript。也许我的代码没有优化,语法也没有优化,但它对我有用。
对于我来说,在onClick中使用字符串转义有几个问题,随着参数数量的增长,它将变得难以维护。
下面的方法将具有一跳-点击-将控件带到处理程序方法,处理程序方法基于事件对象,可以扣除点击事件和相应的对象。
它还提供了一种更清晰的方式来添加更多参数,并具有更大的灵活性。
<button type="button"
className="btn btn-default"
onClick="invoke"
name='gotoNode'
data-arg1='1234'>GotoNode</button>
在JavaScript层:
invoke = (event) => {
let nameOfFunction = this[event.target.name];
let arg1 = event.target.getAttribute('data-arg1');
// We can add more arguments as needed...
window[nameOfFunction](arg1)
// Hope the function is in the window.
// Else the respective object need to be used
})
}
这里的优点是我们可以根据需要拥有任意多的参数(在上面的例子中,data-arg1, data-arg2等)。
let task = {....}
<button onclick="myFunction('${task}')">Continue task</button></li>
多个参数:
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>'
);