gpt4 book ai didi

javascript - 将具有特定参数的函数绑定(bind)到 Javascript 中的 onclick 事件

转载 作者:行者123 更新时间:2023-11-29 23:53:21 24 4
gpt4 key购买 nike

<分区>

我想在这样的上下文中将具有特定参数的函数绑定(bind)到 .onclick():

for(var i = 0; i < 3; i++) {
for(var j = 0; j < 3; j++) {
var button = document.createElement("button");
button.textContent = board[i][j];
button.onclick = function() {
makeMove(i,j); //The function will always be called with the last value of i and j.
}
document.body.appendChild(button);
}
}

我可以通过使用 makeMove.bind(null,i,j)function(arg1,arg2){ return function() { makeMove(i,j); 来解决这个问题}}(i,j) 但两者似乎都不对,因为创建 Function.prototype.bind() 是为了将上下文绑定(bind)到 this 而我不不想使用 IIFE,因为它是初学者程序员的 TicTacToe 示例。

有没有另一种方法可以解决这个问题而不用太复杂?

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com