<a>nchor&#39;s href being overridden by containing <div>&#39;s onclick</div></a>

时间:2012-03-21 18:15:18

标签: javascript jquery html onclick event-bubbling

当我点击外部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();
}

为什么我的点击不在网址后面?

谢谢:)

2 个答案:

答案 0 :(得分:4)

使用.stopPropagation():

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

<强> jsFiddle example

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

答案 1 :(得分:0)

我在click上有另一个.icon处理程序返回false。我的坏人,伙计们!谢谢你的帮助!

相关问题