Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
812 views
in Technique[技术] by (71.8m points)

jquery - Intercept click event on a button, ask for confirmation, then proceed

Based on a variable SomeCondition, I need to intercept a click event on a button, and ask for confirmation, if they say ok, proceed, otherwise ignore click.

So something like:

if(SomeCondition) {

// disable click on button

var isOk = window.confirm("Are you sure?");

if(isOk) {
        $("#button1").click();
}

}

Note: button1 has already been wired up with a click event via javascript from an external .js file that I can't change.

I don't know what the click event was bound too, so I have to disable the click if SomeCondition is true, then ask for confirmation, then continue with the click.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Process isOK your window.confirm within the function of the button

$('#button1').click(function(){ 
   if(window.confirm("Are you sure?"))
     alert('Your action here');
});

The issue you're going to have is the click has already happened when you trigger your "Are You Sure" Calling preventDefault doesn't stop the execution of the original click if it's the one that launched your original window.confirm.

Bit of a chicken/egg problem.

Edit: after reading your edited question:

    var myClick = null;

    //get a list of jQuery handlers bound to the click event
    var jQueryHandlers = $('#button1').data('events').click;

    //grab the first jquery function bound to this event
    $.each(jQueryHandlers,function(i,f) {
       myClick = f.handler; 
       return false; 
    });

    //unbind the original
    $('#button1').unbind('click');

    //bind the modified one
    $('#button1').click(function(){
        if(window.confirm("Are You Sure?")){
            myClick();
        } else {
            return false;
        }
    });

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...