twitter-bootstrap 超时后不显示 Bootstrap Modal 的 setTimeout

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/16512671/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-21 17:07:06  来源:igfitidea点击:

setTimeout with Bootstrap Modal not displaying after time out

javascriptjquerytwitter-bootstrapmodal-dialogsettimeout

提问by Nick

I'm trying to delay showing a Bootstrap modal until 5 seconds have passed. Here is the section of my code. It seems write from what I have read on MDN. The modal does not appear after any amount of time. Any help would be appreciated.

我试图延迟显示 Bootstrap 模式,直到 5 秒过去。这是我的代码部分。似乎是根据我在 MDN 上阅读的内容写的。模态在任何时间后都不会出现。任何帮助,将不胜感激。

var timeout;
  function modalAlert(message){
        $("#myModalLabel").text("Hey Look!")
        $('.modal-body').html("<img src='"+message+"'>");
        timeout = window.setTimeout(showModal,5000);

  }
  function showModal(){
    console.log("HERE")
    $("#myModal").modal('show')
  }

Vijay Ramamurthy helped me find the solution:

Vijay Ramamurthy 帮我找到了解决方案:

var timeout;
  function modalAlert(message){
        $("#myModalLabel").text("Hey Look!")
        $('.modal-body').html("<img src='"+message+"'>");
        window.setTimeout(function(){showModal();},5000);

  }
  function showModal(){
    console.log("HERE")
    $("#myModal").modal('show')
  }

回答by Andy Brudtkuhl

Use the "shown" event handler to register a timeout on the modal and then hide it. You can chain the functions together since it's a jQuery plugin.

使用“显示”事件处理程序在模态上注册超时,然后隐藏它。您可以将这些功能链接在一起,因为它是一个 jQuery 插件。

$("#myModal").modal("show").on("shown", function () {
    window.setTimeout(function () {
        $("#myModal").modal("hide");
    }, 5000);
});

回答by vijrox

try making the last line in the modalAlert function

尝试在 modalAlert 函数中制作最后一行

timeout = window.setTimeout(function () {showModal();}, 5000);