jQuery click事件可以结合回调吗?

时间:2014-04-26 04:40:00

标签: jquery events callback click

我想用OK按钮显示确认弹出窗口。通常,如果我不想回调,那么OK按钮将隐藏弹出窗口和图层蒙版。当我回调然后单击OK按钮将在回调函数中执行某些操作。

function displayErrorPopup(message, callback) {
$("#error_popup_message").html(message);
display_popup($("#error_popup"));
if (callback && typeof (callback) === "function") {
    $("#error_popup_ok").click(function() {
        callback();
    });
} else {
    $("#error_popup_ok").click(function() {
        hideErrorPopup();
    });
}}

但回调函数在调用时立即运行:

displayErrorPopup('error message', function(){
do something;
hideErrorPopup();});

没有按钮事件点击。

请帮帮我!! 谢谢!

2 个答案:

答案 0 :(得分:2)

function displayErrorPopup(message, callback) {
    $("#error_popup_message").html(message);

    display_popup($("#error_popup"));

    $("#error_popup_ok").click(function() {
        if (typeof callback == "function") {
            callback();
        } else {
            hideErrorPopup();
        }
    });
}

更简化的方式是:

function displayErrorPopup(message, callback) {
    $("#error_popup_message").html(message);

    display_popup($("#error_popup"));

    $("#error_popup_ok").click(typeof callback == "function" ? callback : hideErrorPopup);
}

答案 1 :(得分:1)

根据你的评论,

创建了一个fancybox提醒小提琴。这里是链接jsfiddle引用它。

function fancyConfirm(msg,callback) {
var ret;
jQuery.fancybox({
    modal: true,
    content: "<h3>Confirmation:</h3><br/><div style=\"margin:1px;width:340px;\">"+msg+"<div style=\"text-align:right;margin-top:10px;\"><input id=\"fancyConfirm_cancel\" style=\"margin:3px;padding:0px;height:30px;width:80px;\" class=\"greenbtn\" type=\"button\" value=\"Cancel\"><input id=\"fancyConfirm_ok\" style=\"margin:3px;padding:0px;height:30px;width:80px;\" class=\"greenbtn\" type=\"button\" value=\"Ok\"></div></div>",
    afterShow: function() {
        $("#fancyConfirm_cancel").click(function() {
            ret = false;
            jQuery.fancybox.close();
        });
        $("#fancyConfirm_ok").click(function() {
            ret = true;                  
            jQuery.fancybox.close();
        });
    },
    afterClose: function() {
        callback.call(this,ret);
    }
});
}


function fancyConfirmAlert() {

   fancyConfirm("Are you sure you want to perform action.<br/><br/>",  function(ret) {
     alert('done + return values is -> ' + ret);
   });
 }

fancyConfirmAlert() ;