【问题标题】:How to return the value of SweetAlert2 input?如何返回 SweetAlert2 输入的值?
【发布时间】:2020-03-29 01:04:14
【问题描述】:

这是我当前的代码

function getInput() {
  Swal.fire({
    input: "text",
  }).then((result) => {
    if (result) {
      return(result.value);
  });
}

function main() {
  if (condition) {
    const test = getInput();
  } else {
    // do something else
  }
}

我知道这是不正确的,因为它返回未定义。我尝试寻找一堆解决方案,但我总是得到未定义或承诺本身返回,不知道我应该如何获得价值。

我想做的是以某种方式返回 SweetAlert2 输入的值,以便我可以在其他函数中使用它。

编辑

我想我大部分都得到了我想做的事情。我没有将then 处理程序放在getInput() 中,而是将它放在test 中,这样我就可以将其余代码放在处理程序中。

function getInput() {
  return Swal.fire({
    input: "text",
  })
}

function main() {
  if (condition) {
    const test = getInput();
    test.then((result) => {
      if (result) {
        // do stuff
      }
    });
  } else {
    // do something else
  }
}

【问题讨论】:

    标签: javascript sweetalert2


    【解决方案1】:

    使用callback 的理想用例,因为您的程序不确定何时返回该值。

    then 处理程序中,将调用回调函数并将input 作为参数传递。

    function getInput(cb) {
      Swal.fire({
        input: "text",
      }).then((result) => {
          if (result) {
            return cb(result.value);
          });
      }
    }
    
    function main(input) {
      console.log(input);
    }
    
    getInput(main)

    【讨论】:

    • 我明白了,我可能可以使用我的代码来处理这个问题,但这并不理想,因为我的main() 函数有一个 if 条件来控制是否使用 SweetAlert2。使用回调需要我将条件放在外面,这基本上消除了main() 函数的目的。我编辑了我的代码示例来说明我的意思。
    • 你是说maingetInput是独立的函数吗? @宇宙
    • 如果是这种情况,我会将input 的值存储在全局变量中,其余代码将基于global 变量。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-04-10
    • 2011-06-26
    • 1970-01-01
    相关资源
    最近更新 更多