javascript - OnClick后的返回值

标签 javascript jquery promise jquery-deferred

我正在尝试从按钮单击中检索值并将其存储在变量中。问题是用户可以任意单击按钮,而我试图在运行时记录按钮单击的结果。我一直在阅读有关 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/

相关文章:

jquery - 获取 flask 数据请求

javascript - 连接 RESTful API 时如何正确处理无法连接错误

node.js - NodeJs 中被拒绝的 Promise 解析

javascript - 在所有异步函数完成后执行一个函数?

javascript - For循环不重置条形图数据

javascript - jQuery:如何精确匹配 Div 类

javascript - 如何将 mysql 查询的结果放入 html 文本框中

javascript - $ ('#Form' ).submit 与 $.post

javascript - 如何仅提取没有 html 标记的文本?

javascript - MongoDB - 仅在嵌套数组中存在时更新所有条目