简体   繁体   中英

Is there a way to capture the alert ok button click event?

Is there a way to capture the alert ok button click event? In jQuery?

The alert() function is synchronous and you can't verify what was clicked (it does not return anything), so the code below the call will be executed after it is closed (ok or close button). The alert is not used to gain user input. It is an alert, a message to the user. If you need to check what the user want, you should use confirm() . Note that the function name tells its purpose like alert.

Something like:

// if the ok button is clicked, result will be true (boolean)
var result = confirm( "Do you want to do this?" );

if ( result ) {
    // the user clicked ok
} else {
    // the user clicked cancel or closed the confirm dialog.
}

Alert is a blocking function, means, if you don't close it, the code below will not execute. So you don't have to capture the alert close event, just write down the code below that alert, when alert window will be closed the code below will be executed automatically.

See example below:

 alert("Close Me"); // Write down the code here, which will executed only after the alert close console.log("This code is executed after alert")

Disclaimer: This is a very bad thing to do.

Technically you could hook into it with this code:

window.alert = function(al, $){
    return function(msg) {
        al(msg);
        $(window).trigger("okbuttonclicked");
    };
}(window.alert, window.jQuery);



$(window).on("okbuttonclicked", function() {
    console.log("you clicked ok");
});

alert("something");

Demo: http://jsfiddle.net/W4d7J/1/

There is no event for the window.alert(). Basically the next line after it is called when they click ok. I am not sure why you would need to listen for it.

You could use JAlert and assign a click handler to the ok button.

Something like

jAlert("Alert message goes here."); 
$('#popup_ok').bind('click',function(){
   //Do operation after clicking ok button.
   function_do_operation();
});

I tried this in a site I created and it worked perfectly:

<a href="javascript:var rslt=confirm('Cancel Appointment Creation');if(rslt){window.open('http://www.the_website_I_want_to_navigate_to.com')}else{}"> << Back </a>

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