【问题标题】:how to run javascript statement by order如何按顺序运行javascript语句
【发布时间】:2012-09-12 15:04:20
【问题描述】:

我想先显示一条消息,然后重定向我的页面:

toastr.success('Your report has been submitted successfully.');
window.location = '/Report';

但是上面的代码允许两个语句同时运行。结果,重定向发生在显示 toastr 消息之前,这需要时间..

对于这种情况,我们有类似 $.when(...).done(...) 的东西吗?

---更新---

如果有人不知道toastr,它是一个在网页上显示消息的库。

当然设置一个计时器会起作用。但是有没有什么优雅的方法可以在第一个语句完成后运行第二个语句?

【问题讨论】:

  • 这个toastr.success(函数有什么作用?以及为什么你认为你的脚本会在那一行等待?
  • 成功方法有什么作用需要时间?
  • 也许我们会在 toast 消失时从 toastr 返回一个承诺。我还没有对此进行研究,但可以随意将其添加到 github 上的功能请求列表中。在这种情况下,它需要最新版本的 jquery,所以如果有一种方法可以消除它并获得该功能,我会考虑它。但是,是的,将其添加到 github 列表中。

标签: javascript jquery toastr


【解决方案1】:

你可以使用 setTimeout :

toastr.success('Your report has been submitted successfully.');
setTimeout(function(){window.location = '/Report';}, 2000);

【讨论】:

  • 是的,它会工作,但有点难看。我们可以在toastr.success 完成后让重定向发生吗?任意等待 2000ms 绝对不是一个好的解决方案。
  • 这个答案真的是我们唯一的解决方案吗?
【解决方案2】:

您可以将函数作为回调传递,以便在函数完成后执行。请查看有关此类似问题的所选答案:How should I call 3 functions in order to execute them one after the other?

【讨论】:

    【解决方案3】:

    我使用 toastr onHidden 选项取得了很大的成功。它基本上是一个事件回调,允许您设置重定向 url,在 toast 关闭或隐藏时触发。

    // Notify the user of success and redirect when the toast closes
    toastr.options.onHidden = function () {
         window.location.href = <YOUR REDIRECT URL>;
    };
    
    // Fire the success toast which is bound to the onHidden function                    
    toastr.success('Success!<br/><br/>You\'ll now be automatically redirected to your current items.', 'Download Success', { timeOut: 3000, closeButton: true, positionClass: 'toast-bottom-right', progressBar: true });
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-10-17
      • 2023-04-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-03-05
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多