javascript - 在停止元素的其他事件处理程序时插入元素的确认行为

标签 javascript jquery

目标:我希望能够将给定元素的确认行为与其可能绑定(bind)到它的其他事件处理程序分离。所以给出以下简单的例子

var someApp = {
  "init": function(){
     $("a").click(someApp.doAnchorStuff); 
     $("button").click(someApp.doButtonStuff); 
     $("#submitButton").click(someApp.doSubmitStuff); 
     $("a, button, #submitButton").click(someApp.confirmAction); 
    }, 
  "doAnchorStuff": function(){//stuff},
  "doButtonStuff": function(){//stuff},
  "doSubmitStuff": function(){//stuff},
  "confirmAction" : function(){
        //intercept the flow of control and freeze everything, no other 
        //handlers on the elements this is being triggered on get called
        //display confirm dialog. 
        //IF user confirms, unfreeze, let the other handlers get triggered. 
        //If Not, do not let other event handlers get triggered
}
}

$(function(){
    someApp.init(); 
});

如果这没有意义,我很乐意澄清。

一个不工作的 fiddle 示例 :) http://jsfiddle.net/7jbt9/

最佳答案

要完成这项工作,您需要做两件事:

  1. 需要首先附加 confirmAction 点击​​处理程序。这样做将使它在链中首先执行。

  2. 对传递给回调函数的事件对象调用 stopImmediatePropagation() 方法。这将停止执行该事件的任何其他回调。

"confirmAction": function(e) {
    if (!confirm("Continue?")) {
        e.stopImmediatePropagation();
    }
}

关于javascript - 在停止元素的其他事件处理程序时插入元素的确认行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18085720/

相关文章:

javascript - 使用纯 JavaScript 通过在其他地方单击打开后单击关闭来关闭 div

javascript - HTML/Javascript addEventListener Onchange 事件在 Onchange 中?

javascript - NodeJS 函数没有返回数据

javascript - 单击动态创建的 DOM

jquery - 如何禁止将大文件添加到文件输入

javascript - 转换为指令的 jQuery 函数在 Angular 上不起作用

Javascript提交仅影响while循环php中的第一个div

javascript - 将文本输入值更新到段落中的问题

javascript - 输入时将文本框值附加到文本区域

jquery - 如何使用 jquery 触发此页面转换?