jQuery UI对话 - X秒后关闭

时间:2012-08-12 20:09:59

标签: javascript jquery jquery-ui settimeout

这段代码完美无缺,除了 - 对话窗口在X毫秒后不会关闭,因为我期待......

setTimeout函数被执行(我把alert()放在那里它工作了......),所以我假设问题是$("#alert div").dialog('close');,但我不知道出了什么问题...

if ($("#alert").length) {
    var title;
    if ($("#alert span").length) {
        title = $("#alert span").text();
    }
    $("#alert div").dialog({
        title: title,
        modal: true,
        open: function() {
            setTimeout(function() {
                $("#alert div").dialog('close');
            }, 2000);
        }
    });
}

编辑: 如果有帮助,这里是HTML:

<div id="alert">
    <span>Password change</span>
    <div>Password was successfully changed.</div>
</div>

已解决!如果有人有想法,为什么我的代码不起作用会很棒......

2 个答案:

答案 0 :(得分:10)

您有一个范围问题。试试这个 jsFiddle example

if ($("#alert").length) {
    var title;
    if ($("#alert span").length) {
        title = $("#alert span").text();
    }
    $("#alert div").dialog({
        title: title,
        modal: true,
        open: function() {
            var foo = $(this);
            setTimeout(function() {
               foo.dialog('close');
            }, 2000);
        }
    });
}​

这种情况发生的原因并没有像你预期的那样工作,这是由于你引用成为对话框的目标div的方式,以及jQuery UI构建对话框的方式。如果您查看开发人员控制台,您将看到jQuery将您的div从DOM中的原始位置拉出来,因此#alert div不再可以引用它,因为它不再是#alert的孩子。如果你给了div这个自己的ID,它会按预期工作,你不需要临时变量来引用它。

答案 1 :(得分:0)

经过测试和现场演示:

http://jsfiddle.net/oscarj24/q6tD9/2/

我认为这种方式更好:

jQuery.fn.exists = function(){return this.length>0;}

$(function() {
    if($('#alert').exists()){
        var modal = $('#alert div');
        modal.dialog({ title: $('#alert span').text(), modal: true });
        var opened = modal.dialog('isOpen');
        if(opened){
            setTimeout(function(){ 
               modal.dialog('close'); 
            }, 2000);
        }
    }
});​
相关问题