我正在使用 p5.js 来使用按钮与 Sprite 的交互。我只是有一个关于通过 for 循环创建按钮的快速问题。我知道我可以轻松地为 4 个按钮中的每一个创建单独的对象,但我想看看它如何以这种方式工作,只是为了使代码更短。
我想让每个按钮都调用一个函数“puton(i)”,并在 for 循环中增加 i,这样每个按钮就可以做不同的事情(在我的例子中就是穿上不同的衣服)。但是,我收到此错误:
Uncaught TypeError: Cannot read property 'bind' of undefined.
我不太了解参数在 javascript 中的工作原理,因此我可能会犯下严重错误,因此对更有效的方法(除了对每个按钮进行硬编码之外)的一些见解也将受到赞赏。
提前致谢!
var hat, shirt, pants, shoes;
function setup(){
createCanvas(500, 300);
background(155);
var clothes = ["Hat", "Shirt", "Pants", "Shoes"]; // Just to make the code clean.
for(var i = 0; i < clothes.length; i++){
var change = createButton('Put on ' + clothes[i]);
change.position(10, i*30 + 60);
change.mousePressed(puton(i));
}
}
function puton(i){
console.log(i); //To test, "0" gets printed, but after that it crashes.
}
最佳答案
.mousePressed()
采用函数作为其参数,而不是函数调用。
官方文档中有一个很好的例子:https://p5js.org/reference/#/p5.Element/mousePressed
这适用于您的情况:
change.mousePressed(puton);
甚至是这个:
change.mousePressed(function(e) {
console.log(e);
});
关于javascript - "Uncaught TypeError: Cannot read property ' 在 p5.js 上绑定(bind) ' of undefined",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41082376/