从另一个函数中关闭jquery ui modal

时间:2011-09-22 19:53:08

标签: jquery regex jquery-ui jquery-ui-dialog

一次。 我有一个使用jQuery UI插件生成内联模式窗口的脚本,如下所示:

function openModal(src, width, title){
    $("#" + src).dialog({
        modal: true,
        width: width,
        title: title,
        resizable: false,
        show: 'fade',
        hide: 'fade'
    });
    $('.ui-widget-overlay').hide().fadeIn();
    return false;
}

$(document).ready(function() {
    $('#newTopicBtn').click(function(e) {
        e.preventDefault();
        openModal('newTopic', 650, 'New Topic');
    });
});

模态窗口就像它应该弹出一样。

这些模态窗口中的大多数都打开了某种形式。问题是当表单被提交并由脚本处理时,当我使用$('#newTopic').dialog("close")时,我似乎无法使表单的模态自行关闭:

$('#newTopic_form').bind('submit', function() {
    var error = '';

    var topicTitle = $('input[name=newTopicTitle]').val();
    var topicBody = $('textarea[name=newTopicBody]').val();

    if(topicTitle == '' || topicTitle.length < 2)
    {
        error = error + '<br />You must enter a longer title.';
    }
    if(topicBody == '' || topicBody.length < 2)
    {
        error = error + '<br />You must enter a longer topic.';
    }

    if(error != '')
    {
        $('#newTopicError').css("display","none");
        $('#newTopicError').html(error);
        $('#newTopicError').fadeIn(1000);
    }
    else
    {
        var pageUrl = window.location.search;
        var pattern = /mode=viewcat&id=(\d+)&title/gi;
        var catID = pageUrl.match(pattern);

        var data = 'mode=newTopic&cat_id=' + catID + '&title=' + encodeURIComponent(topicTitle) + '&content=' + encodeURIComponent(topicBody) + '&u=' + usrId;
        $.ajax({
            url: "data.php",
            type: "POST",
            dataType: "json",
            data: data,
            cache: false,
            success: function(data) {
                if(data.response == 'added')
                {
                    $('#newTopicError').css("display", "none");
                    $('#newTopicError').html("You have added your topic.");
                    $('#newTopicError').fadeIn(1000);
                    setInterval(10000, function(){
                        $('#newTopic').dialog("close");
                    });
                }
            }
        });
    }
    return false;
});

表单提交并处理完全正常,正确的字符串淡入模态的表单响应区域,但窗口永远不会关闭。

我的RegEx也存在一个问题,因为它只返回null而不是catID,如果有人想帮助那个。 :)

1 个答案:

答案 0 :(得分:3)

我认为

setInterval(10000, function(){
    $('#newTopic').dialog("close");
});

应该是:

setTimeout(function(){
    $('#newTopic').dialog("close");
}, 10000);

原始代码的参数顺序错误,并且表示您希望每隔 10秒关闭对话框。新代码的参数顺序正确,只能执行一次,10秒。