jQuery UI Dialog Auto-Close using setTimeout

2020-07-06 06:27发布

问题:

I'm trying to have my dialog auto-close three seconds after opening. I've tried the following methods:

setTimeout($("#mydialog").dialog('close'), 3000);

Here it is in context:

$("#acknowledged-dialog").dialog({
    height: 140,
    modal: true
});

setTimeout($("#acknowledged-dialog").dialog('close'), 3000);

But with this method, it doesn't even show! I'm guessing the the close method is getting called immediately after it gets shown on the page. The log shows no errors.

I've also tried binding to the dialogopen event:

$("#acknowledged-dialog").bind('dialogopen', function(event, ui) {
    setTimeout($(this).dialog('close'), 3000);
});
$("#acknowledged-dialog").dialog({
    height: 140,
    modal: true
});

The dialog shows, but does not auto-close. No error in the logs here either.

Am I not able to use 'this' in the argument for $ in setTimeout?

回答1:

setTimeout is calling on the the return value of $("#mydialog").dialog("close") after 3 seconds. you want to throw the whole thing as a string, and it should work just fine. Also, I don't think you want to bind 'dialogopen' before you initialize the dialog. Below should work just fine:

$("#acknowledged-dialog").dialog({
    height: 140,
    modal: true,
    open: function(event, ui){
     setTimeout("$('#acknowledged-dialog').dialog('close')",3000);
    }
});


回答2:

I wrote an article specifically for the problem you are experiencing. Please read that.

In short, you want to wrap $("#mydialog").dialog('close') with an inline function everywhere you want it executed as a result of a delay or a triggered event.

setTimeout(function(){
    $("#mydialog").dialog('close')
}, 3000);

The dialog doesn't even show because you closed it as soon as you opened it in each case.