【问题标题】:Prevent one jQuery Event with another防止一个 jQuery 事件与另一个事件发生
【发布时间】:2011-09-11 15:14:42
【问题描述】:

为了整理我的 jQuery,我希望使用事件处理程序为各种元素创建一个“确认”类,以便我可以触发一个快速确认框,以便用户确认他们的操作。

如果用户点击确认框上的取消,任何后续事件都应该被取消,但这应该不是是永久性的,例如再次触发该事件应该带来确认并重新开始。如果我能解决这个问题,我可以让任何敏感操作都有一个确认问题,以确保用户想要点击。

例如:

$('.confirm').click(function() {
    if(!confirm('Are you sure?')) {
        // Stop any other click events on $(this) from happening this instance.
    }
});

$('.clicker').click(function() {
    alert('it happened');
});

<a class="clicker confirm">Click me</a>

期望的输出是取消确认会取消点击事件,但不会完全禁用它。

【问题讨论】:

    标签: jquery events onclick event-handling


    【解决方案1】:
    $('.confirm').click(function() {     
    return confirm('Are you sure?');
    });
    

    您还可以在点击事件中使用event.stopPropagation() 来停止进一步的传播。

    【讨论】:

    • 我发现return false并没有阻止触发其他点击事件。
    • 遗憾的是,.disablePropagation() 不存在。这是我的错,应该是.stopPropagation(),这也不起作用。 Nicola 提出了正确的解决方案!
    【解决方案2】:

    你可以使用 jQuery 中的event.stopImmediatePropagation()

    $('.confirm').click(function(event) {
        if(!confirm('Are you sure?')) {
            event.stopImmediatePropagation();
    
            // Stop any other click events on $(this) from happening this instance.
        }
    });
    
    $('.clicker').click(function() {
        alert('it happened');
    });
    

    test case on jsFiddle

    【讨论】:

    • 谢谢!这是我打算做的。在我的回答中搞砸了两次,所以决定删除它;)谢谢你让我振作起来!
    • 我想补充一点,在表单的情况下,当您拒绝确认时,还需要 event.preventDefault() 来阻止表单触发。
    猜你喜欢
    • 2015-07-08
    • 2017-11-08
    • 1970-01-01
    • 1970-01-01
    • 2014-09-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多