【问题标题】:Return Value After OnClickOnClick 后的返回值
【发布时间】:2017-06-12 20:34:24
【问题描述】:

我正在尝试从按钮单击中检索一个值并将其存储在一个变量中。问题是用户可以任意单击按钮,我试图在运行时记录按钮单击的结果。我一直在阅读有关 Promise 的内容,如果有必要的话,我不确定如何在我当前的代码中实现它们。我不确定我是否应该担心返回结果,而是将变量传递给下一个函数调用。

startGame()

$("#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();
});

【问题讨论】:

  • 如果您只想在单击按钮时记录值... $("#play_btn").click(function() {console.log(icon)}
  • 我知道我能做到。我希望它存储在主函数调用中。为此,需要将其退回。
  • 如果按钮可以被点击一次可能 用承诺来做到这一点。是否有必要很难说。你能提供一个工作样本吗?
  • 我认为这对于 Promise 来说不是一个好的用例。当用户决定他玩哪一边时,可以简单地将其存储在一个全局变量中,比如 var player="x"; ...

标签: javascript jquery promise jquery-deferred


【解决方案1】:

使用 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);
});

但是,我不知道这是否真的有用。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-02-16
    • 1970-01-01
    • 1970-01-01
    • 2014-12-06
    • 2015-06-20
    相关资源
    最近更新 更多