简体   繁体   中英

Dedicated event handler for close (x) button in jQuery UI Dialog

Is there a way to wire into the close (x) button on a jQuery UI Dialog, such that you can provide a dedicated event handler? Using the "close" or "beforeclose" event does not work because if you have other buttons in your dialog that also cause the dialog to close, you are always going to hit the "close" and "beforeclose" events, which is not desirable. I want a way to run specific code from the close (x) button.

Whenever one event leads to another event inside a jQuery UI widget, the original event is always included in the event object. In this case, you can look at the event object passed to the close callback or the dialogclose event and check if event.originalEvent exists. If it does, then you can assume that the dialog was closed via a click on the close button. This also applies to beforeclose .

If you want to be absolutely sure that it was the close button in the titlebar, then you can check event.originalEvent.target and either check the class or the DOM location using .closest() .

Here's a jsbin showing this in action: http://jsbin.com/ajoheWAB/1/edit

You could try:

$(document).on('click','.ui-dialog-titlebar-close',function(){
    //close button clicked
});

As far as I know there's no way to wire directly to that button, but you can do something specific to your popup by adding a dialogClass and wiring an event handler yourself:

var dialogClass ="yourPopupTitle";

$(document).on('click', '.'+ dialogClass  +' .ui-dialog-titlebar-close', function() { 
    handleEvent();
});

FIDDLE

I believe this is the solution you are looking for - you will need to unbind the click event and re-bind your custom handler to it.

Although this thread is old, I'd still add my solution here with a hope to benefit others who search for it.

var fnCustomerHandler = function() {
    alert("Here is your custom handler...");  
};

$( "#dialog" ).dialog({
        open: function(event, ui) {
            var el = $(this).closest('.ui-dialog').find('.ui-dialog-titlebar-close');
            el.off();
            el.on("click", fnCustomerHandler);
        }
    }
);

Fiddle link:

http://jsfiddle.net/morefool/n82649d5/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM