jQuery 直到函数执行后对话框才会关闭

jQuery dialog box not closing till a function is executed

我正在使用 jquery 对话框提醒用户删除 table 中的记录。以下是我的代码:

$('#deletebutton').click(function () {
    if($(this).attr('disabled')=='disabled'){
        //do nothing
    }
    else{
        var isDeleteYes = false;
        $('#delete-confirm').dialog({
                    height : 150,
                    width : 400,
                    autoOpen : true,
                    close: function( event, ui ) {
                        //alert(closed)
                    },
                    buttons : {
                        "Yes" : function () {
                            isDeleteYes = true;
                            $(this).dialog("close");
                            deleteFunction();

                        },
                        "No" : function () {
                                    isDeleteYes=false;
                                    $(this).dialog("close");
                                }
                    },
                    title : "Confirm Delete",
                    resizable : false,
                    modal : true,
                    overlay : {
                        opacity : 0.5,
                        background : "black"
                    }
                });


    }
 });
 function deleteFunction(){
   /*
    *
    * Logic for delete
    *
    */

 }

问题是,在“是”按钮中,我在函数调用 deleteFunction() 之前关闭了对话框。但在函数完成执行之前它不会关闭。一旦我单击是或否,关闭功能中的警报就会出现。但是对话框没有在 UI.

中关闭

根据您的描述,这是因为您在 deleteFunction 中 运行 进行同步操作,(这意味着一个脚本将 运行 接一个,如果异步意味着将 运行平行)。

$(this).dialog("close"); 脚本将仅更新 dom 以隐藏元素,以隐藏浏览器重绘视图中的元素。

在浏览器中,javascript 和 repaint/reflow 在同一个线程中运行 运行s(但同步),这意味着前一个脚本完成后将 运行 执行操作, 因此即使对话框被标记为隐藏,它也不会从视图中隐藏,除非当前脚本执行结束,并且浏览器有机会执行重新流。

解决问题的一个捷径是使用超时,如果你想在异步模式下执行删除功能,如下所示

"Yes": function () {
    isDeleteYes = true;
    $(this).dialog("close");
    setTimeout(deleteFunction, 1);

},

如果您在调用的方法 (deleteFunction) 中调用 ajax,则将其设为 "async: true"。它对我来说很好用。希望能成功。