【问题标题】:<A>nchor's href being overridden by containing <div>'s onclick<A>nchor 的 href 被包含 <div> 的 onclick 覆盖
【发布时间】:2012-03-21 18:15:17
【问题描述】:

当我点击外部 div 内的以下链接时,我得到 confirm 语句,但点击“确定”后,什么也没有发生。

HTML:
<div onclick="toggleExerciseDetails($(this),true)" class="clickable">
...
    <a target="_blank" href="http://iPUMPit.local/exercises/delete/275"
        onclick="cancelPropagation(event);return confirm('Are you sure you want to delete this exercise?');"
        title="Delete this exercise" class="icon icon_delete"></a>
</div>

JavaScript:

// cancels propagation of an event to the outer element event
function cancelPropagation(e) {
    if (!e)
        var e = window.event;
    e.cancelBubble = true;
    if (e.stopPropagation) e.stopPropagation();
}

为什么我的点击没有跟随 url?

谢谢:)

【问题讨论】:

  • 如果您将整个 onclick 替换为 return True ,它会做您想要的吗?这就是你的确认所做的一切,我认为这不是你的目标。
  • 你想用这个做什么?您可能希望发布您的toggleExerciseDetails() 方法。看起来你正在使用 jquery。
  • 但是让我们从头开始。 toggleExerciseDetails 会被执行吗?
  • @MrLister:不,如果我点击链接,它永远不会被执行。 @Keeyai:如果我用return true; 替换它,它什么也做不了。 @shanabus:我会,但是在意识到它甚至没有执行之后,没有用。
  • 好的,如果你把&lt;a&gt;&lt;div&gt;中取出,不做任何改变,那么它会起作用吗?

标签: javascript jquery html onclick event-bubbling


【解决方案1】:

使用 .stopPropagation():

$('div.clickable a').click(function(e) {
    e.stopPropagation();
});​

jsFiddle example.

这将使您的链接可点击,但不允许事件冒泡到 div,同时保持 div 可点击。

【讨论】:

  • 你试过 jsFiddle 了吗?在那里工作。也许您有其他代码导致冲突?
  • 从技术上讲,鉴于上述信息,您的答案是正确的,因此您应该打勾。
【解决方案2】:

我在.icons 上有另一个click 处理程序,它返回false。我的坏,伙计们!感谢您的帮助!

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-03-25
    • 1970-01-01
    • 1970-01-01
    • 2017-11-06
    • 1970-01-01
    • 2011-05-16
    • 2020-02-17
    • 1970-01-01
    相关资源
    最近更新 更多