我正在尝试从按钮单击中检索值并将其存储在变量中。问题是用户可以任意单击按钮,而我试图在运行时记录按钮单击的结果。我一直在阅读有关 promise 的内容,但我不确定如何在当前的代码中实现它们(如果有必要的话)。我不确定我是否应该担心返回结果并将变量传递到下一个函数调用中。
开始游戏
$("#play_btn").click(function() {
if ($(".icons i").hasClass("selected")) {
$("h5").remove();
$(".icons").remove();
$("button").remove();
// I can pass the variable into this function, but then I will just be chaining
// function calls. Is this the best route?
// buildBoard calls -> playGame() calls -> endGame()
buildBoard();
return icon;
}
});
主要内容
$("document").ready(function() {
/*
My thought process was to record the icon in the "elements" object
and then call buildBoard() from the document.ready() function after the
user had clicked the button
*/
let elements = {};
var deferred = $.Deferred();
deferred
.then(function() {
return startGame();
})
.done(function(icon) {
console.log(icon);
});
deferred.resolve();
});
最佳答案
使用 promise 看起来像这样:
var chooseSide=new Promise(function(resolve){
$("#play_btn").click(function() {
if ($(".icons i").hasClass("selected")) {
$("h5").remove();
$(".icons").remove();
$("button").remove();
var icon="x";//todo
resolve(icon);
}
});
});
所以你可以这样做
chooseSide.then(function(side){
alert("you chose:"+side);
startGame(side);
});
但是,我不知道这是否真的有用。
关于javascript - OnClick后的返回值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44508275/