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

后端 未结 4 942
陌清茗
陌清茗 2020-12-08 10:33

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.

相关标签:
4条回答
  • 2020-12-08 11:12

    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;
            }
        });
    
    0 讨论(0)
  • 2020-12-08 11:18

    I could not get any of the answers above to work using jquery 1.9.1

    here is what worked for a previously set click event

    var elem = $('#button1');
    var oldClick = $._data(elem[0], 'events').click[0].handler;
    elem.off('click');
    
    // Pass the original event object.
    elem.click(function(e){
      if(window.confirm("Are You Sure?")){
        oldClick(e);
      } else {
        return false;
      }
    });   
    

    very similar to Jason Benson's answer above

    0 讨论(0)
  • 2020-12-08 11:22

    With jQuery to prevent default you just return false:

    $("#button1").click(function () {
        //do your thing
        return false;
    });
    
    0 讨论(0)
  • 2020-12-08 11:22

    To anyone who is looking for a simple solution (not particular to the special condition mentioned here)

    Just add this attribute to the button:

    .... , onclick = "return confirm('are you sure?')"
    

    When the confirmation box returns a false, the click event gets cancelled. Note: The onclick handler explicitly mentioned inline will override any other bindings.

    0 讨论(0)
提交回复
热议问题