0

我正在使用 JQ 对话框来替换本机 js confirm() 函数。要将它用作中心功能,我已将其放入一个功能中。

var dialogID = "dialog_" + createUUID();
var width = 300;
var height = 150;
var url = "";
var formObj = "";
function jqConfirm(dialogID,title,txt,width,height,url,formObj) {
    var dialog = $("#" + dialogID);
    // generate the HTML
    if (!$("#" + dialogID).length) {
        dialog = $('<div id="' + dialogID + '" style="display:hidden;" class="loading"></div>').appendTo('body');
}
dialog.dialog({
    bgiframe: true,
    autoOpen: false,
    width: width,
    height: height,
    minWidth:100,
    minHeight:100,
    maxWidth:980,
    maxHeight:700,
    modal: true,
    dialogClass: 'dialogWithDropShadow',
    resizable:false,
    draggable:false,
    show:'fade',
    hide:'fade',
    title: title,
    buttons: [
        {
            text: "OK",
            "class": 'mscbutton',
            click: function() {
                if (formObj.length) {
                $(formObj).submit();
            } else if (url.length) {
                document.location.href = url;
            }
        $(this).dialog('close');
            }
        },
        {
            text: "Cancel",
            "class": 'mscbutton',
            click: function() {
                $(this).dialog('close');
            return false;
            }
        }
    ],
});
// fill the dialog
$(dialog).html(txt);
dialog.dialog('open');
$(dialog).removeClass('loading');
}

我从其他 JS 文件中调用该函数。一个 js confirm() 我会这样使用:

if (confirm('confirm me')) doThis();

但是这种方式不适用于我的函数,因为我得到的只是“未定义”。

if (jqConfirm(paramstring...)) doThis();

对话框打开并且工作正常,但似乎没有返回任何内容。我知道我做错了什么。但是什么?

谢谢大家的问候

4

1 回答 1

1

你不能那样做。只有内置插件(alertconfirm等)才能真正停止页面上 JavaScript 的执行,等待用户做某事。

相反,您必须使用回调,例如:

jqConfirm(paramstring, function(result) {
    if (result) {
        doThis();
    }
});

jqConfirm您可以使用按钮上的回调触发传入的回调:

// Add `callback` to this somewhere appropriate; I've just stuck it at the
// end. Consider using an options object rather than lots of individual
// parameters.
function jqConfirm(dialogID, title, txt, width, height, url, formObj, callback) {
    // ...
    dialog.dialog({
        // ...
        buttons: [
           {
               text: "OK",
               "class": 'mscbutton',
               click: function () {
                   if (formObj.length) {
                       $(formObj).submit();
                   }
                   else if (url.length) {
                       document.location.href = url;
                   }
                   $(this).dialog('close');
                   callback(true);            // <== Do the callback
               }
           },
           {
               text: "Cancel",
               "class": 'mscbutton',
               click: function () {
                   $(this).dialog('close');
                   callback(false);           // <== Do the callback
               }
           }
        ],
    });
    // ...
}
于 2013-08-02T09:47:35.167 回答