我目前使用jQuery使一个div可点击,在这个div我也有锚。我遇到的问题是,当我点击一个锚都点击事件是发射(div和锚)。我如何防止div的onclick事件从发射时,一个锚被单击?

下面是破碎的代码:

JavaScript

var url = $("#clickable a").attr("href");

$("#clickable").click(function() {
    window.location = url;
    return true;
})

HTML

<div id="clickable">
    <!-- Other content. -->
    <a href="http://foo.example">I don't want #clickable to handle this click event.</a>
</div>

当前回答

所有的解决方案是复杂的和jscript。下面是最简单的版本:

var IsChildWindow=false;

function ParentClick()
{
    if(IsChildWindow==true)
    {
        IsChildWindow==false;
        return;
    }
    //do ur work here   
}


function ChildClick()
{
    IsChildWindow=true;
    //Do ur work here    
}

其他回答

您需要阻止事件到达父节点(div)(冒泡)。 请参阅此处关于冒泡的部分,以及此处特定于jquery的API信息。

要指定某些子元素为不可点击的,请按照下面的示例编写css层次结构。

在这个例子中,我停止传播到一个类为".subtable"的表中td和tr中的任何元素(*)

$(document).ready(function()
{    
   $(".subtable tr td *").click(function (event)
   {
       event.stopPropagation();
   });

});

下面是一个使用Angular 2+的例子

例如,如果你想关闭一个模态组件,如果用户在它外面点击:

// Close the modal if the document is clicked.

@HostListener('document:click', ['$event'])
public onDocumentClick(event: MouseEvent): void {
  this.closeModal();
}

// Don't close the modal if the modal itself is clicked.

@HostListener('click', ['$event'])
public onClick(event: MouseEvent): void {
  event.stopPropagation();
}

使用返回false;或e.stopPropogation ();将不允许执行其他代码。它会在这一点停止流动。

使用stopPropagation方法,见示例:

$("#clickable a").click(function(e) {
   e.stopPropagation();
});

正如jQuery文档所说:

stopPropagation方法防止事件在DOM中冒泡 树,防止任何父处理程序被通知该事件。

请记住,它不会阻止其他侦听器处理此事件(例如。),如果不是想要的效果,你必须使用stopImmediatePropagation代替。