mousePressed 方法在 p5js 中过早启动
mousePressed method is launching prematurely in p5js
我使用 p5.js 创建了以下函数,mousePressed 方法在页面加载时立即触发。它不等我点击按钮对象就显示包含 ans 变量的段落。
我做错了什么?
function setup() {
var ans = generate();
var checkMe = createButton('Check Answer');
checkMe.mousePressed(createP(ans));
}
让我们仔细看看这一行:
checkMe.mousePressed(createP(ans));
这可以分成两行:
var createPValue = createP(ans);
checkMe.mousePressed(createPValue);
换句话说,您正在调用 createP()
函数,然后将返回值(可能是 undefined
)传递给 mousePressed()
函数。我很惊讶这不会在 JavaScript 控制台中导致错误。
相反,您要做的是将函数作为值传递给 mousePressed()
函数。由于您需要使用参数,因此您可以这样做:
function callCreateP(){
createP(ans);
}
checkMe.mousePressed(callCreateP);
请注意,当我们将 callCreateP
传递给 mousePressed()
函数时,其名称后没有括号 ()
。那是因为我们将它作为一个值来使用,而不是直接调用它。
您可以将其缩短为这一行:
checkMe.mousePressed(function(){ createP(ans); });
我使用 p5.js 创建了以下函数,mousePressed 方法在页面加载时立即触发。它不等我点击按钮对象就显示包含 ans 变量的段落。
我做错了什么?
function setup() {
var ans = generate();
var checkMe = createButton('Check Answer');
checkMe.mousePressed(createP(ans));
}
让我们仔细看看这一行:
checkMe.mousePressed(createP(ans));
这可以分成两行:
var createPValue = createP(ans);
checkMe.mousePressed(createPValue);
换句话说,您正在调用 createP()
函数,然后将返回值(可能是 undefined
)传递给 mousePressed()
函数。我很惊讶这不会在 JavaScript 控制台中导致错误。
相反,您要做的是将函数作为值传递给 mousePressed()
函数。由于您需要使用参数,因此您可以这样做:
function callCreateP(){
createP(ans);
}
checkMe.mousePressed(callCreateP);
请注意,当我们将 callCreateP
传递给 mousePressed()
函数时,其名称后没有括号 ()
。那是因为我们将它作为一个值来使用,而不是直接调用它。
您可以将其缩短为这一行:
checkMe.mousePressed(function(){ createP(ans); });