2016-12-11 18 views
0

我正在使用p5.js來使用按鈕與sprite的交互。我只是有一個關於通過for-loops創建按鈕的快速問題。我知道我可以爲4個按鈕中的每一個輕鬆創建單獨的對象,但我想知道如何以這種方式工作,以縮短代碼。「Uncaught TypeError:無法讀取p5.js上未定義的屬性」綁定「

我想讓每個按鈕都調用一個函數「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. 
} 

回答

1

.mousePressed()以函數作爲參數,而不是函數調用。 有官方文檔中一個很好的例子:https://p5js.org/reference/#/p5.Element/mousePressed

這樣的工作,你的情況:

change.mousePressed(puton); 

甚至這樣的:

change.mousePressed(function(e) { 
    console.log(e); 
}); 
相關問題