拦截按钮上的点击事件,要求确认,然后继续

Bla*_*man 22 jquery

基于变量SomeCondition,我需要拦截按钮上的点击事件,并要求确认,如果他们说好,继续,否则忽略点击.

所以类似于:

if(SomeCondition) {

// disable click on button

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

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

}
Run Code Online (Sandbox Code Playgroud)

注意:button1已经通过javascript从外部.js文件连接点击事件,我无法更改.

我不知道点击事件也绑定了什么,因此如果SomeCondition为true,我必须禁用点击,然后要求确认,然后继续点击.

Jas*_*son 40

进程是你的窗口.在按钮的功能内确认

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

你将遇到的问题是,当你触发"你确定"时,点击已经发生了调用.如果启动你的原始window.confirm,则killDefault不会停止执行原始点击.

一点鸡/蛋问题.

编辑:阅读您编辑的问题后:

    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;
        }
    });
Run Code Online (Sandbox Code Playgroud)