简体   繁体   中英

JQuery Dialog - execute code only when clicking “X” Button

I have a dialog with two buttons (Yes-No). Each one triggers a function

$('#divDialog').dialog({
    modal:true,
    width:450,
    resizable: false,          
    buttons: [{
        text: 'Yes',
        click: function () {
            /*Do stuff when clicking yes*/
        }},{
            text: 'No',                
            click: function () {
                /*Do stuff when clicking no*/
            }}],
    close: function(ev, ui){
        /*Do stuff always when closing*/                 
    }
});

What I want to do is execute the same code as in the "No" button when you click the "X" button on top. So I put that code in the "close" function. But then the code is also executed when clicking "Yes".

How can I execute that code when clicking "X" but not when clicking "Yes"?

Thanks.

define a function and call it when user clicks yes or closes dialog.

 $('#divDialog').dialog({
          modal:true,
          width:450,
          resizable: false,          
          buttons: [{
                text: 'Yes',
                click: function () {
                    /*Do stuff when clicking yes*/
                    do_work();
                }},{
                text: 'No',                
                click: function () {
                    /*Do stuff when clicking no*/
          }}],
          close: function(ev, ui){
                     /*Do stuff always when closing*/                 
                    do_work();
                }
       });

function do_work() {
    ....
}

You can do that with declaring on function outside of the jQueryUI init :

var onClick = function(ev, ui) {
    console.log(ev);
    if(ev.type == "click") {
        this.isYes = (ev.originalEvent.currentTarget.textContent == "Yes")
        $(this).dialog('close');
    } else {
        if(this.isYes){
            alert("Yes");
        } else {
            alert("No");
        }
    }
}

$('#divDialog').dialog({
    modal:true,
    width:450,
    resizable: false,          
    buttons: [{
        text: 'Yes',
        click: onClick
    },{
        text: 'No',                
        click: onClick
    }],
    close: onClick
});

jsFiddle

All you need to do is to define a function and call it wherever needed, like below.

Demo@ Fiddle

function myFunction() {
    alert ("I am clicked");
}

$('#divDialog').dialog({
    modal:true,
    width:450,
    resizable: false,          
    buttons: [{
        text: 'Yes',
        click: function() {}
    }, {
        text: 'No',                
        click: myFunction
    }],
    close: myFunction
});

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