首页 文章

如何在单击子锚点时阻止父级的onclick事件触发?

提问于
浏览
267

我目前正在使用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.com">I don't want #clickable to handle this click event.</a>
</div>

16 回答

  • 9

    如果有人需要写作(为我工作):

    event.stopImmediatePropagation()
    

    this解决方案 .

  • 7

    如果您不打算在任何情况下与内部元素交互,那么CSS解决方案可能对您有用 .

    只需将内部元素设置为 pointer-events: none

    在你的情况下:

    .clickable > a {
        pointer-events: none;
    }
    

    或者通常针对所有内部元素:

    .clickable * {
        pointer-events: none;
    }
    

    在使用ReactJS进行开发时,这个简单的黑客为我节省了大量时间

    浏览器支持可以在这里找到:http://caniuse.com/#feat=pointer-events

  • -5

    使用 return false;e.stopPropogation(); 将不允许执行更多代码 . 它会在此时停止流动 .

  • 1

    如果可点击的div中有多个元素,则应执行以下操作:

    $('#clickable *').click(function(e){ e.stopPropagation(); });
    
  • 8

    使用stopPropagation方法,查看示例:

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

    正如jQuery Docs所说:

    stopPropagation方法可防止事件冒泡DOM树,从而阻止任何父处理程序收到事件通知 .

    请记住,它不是 prevent others listeners to handle this event (例如,按钮的多个单击处理程序),如果它不是所需的效果,则必须使用 stopImmediatePropagation .

  • -3

    在这里,我的解决方案适合所有人在那里寻找非jQuery代码(纯javascript)

    document.getElementById("clickable").addEventListener("click", function( e ){
        e = window.event || e; 
        if(this === e.target) {
            // put your code here
        }
    });
    

    如果单击父母的孩子,您的代码将不会被执行

  • 5

    事件冒泡到DOM附加了单击事件的最高点 . 因此,在您的示例中,即使您在div中没有任何其他明确可单击的元素,div的每个子元素也会将它们的click事件向上冒泡到DOM,直到DIV的click事件处理程序捕获它为止 .

    有两个解决方案是检查谁实际发起了事件 . jQuery传递一个eventargs对象和事件:

    $("#clickable").click(function(e) {
        var senderElement = e.target;
        // Check if sender is the <div> element e.g.
        // if($(e.target).is("div")) {
        window.location = url;
        return true;
    });
    

    您还可以将单击事件处理程序附加到链接,这些处理程序在执行自己的处理程序后告诉它们stop event bubbling

    $("#clickable a").click(function(e) {
       // Do something
       e.stopPropagation();
    });
    
  • 87

    你也可以试试这个

    $("#clickable").click(function(event) {
       var senderElementName = event.target.tagName.toLowerCase();
       if(senderElementName === 'div')
       {
           // do something here 
       } 
       else
       {
          //do something with <a> tag
       }
    });
    
  • 11

    这是使用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();
    }
    
  • -3

    您需要阻止事件到达(冒泡)到父(div) . 请参阅有关冒泡here和jQuery特定API信息here的部分 .

  • 0

    要将某个子元素指定为unlickable,请编写css层次结构,如下例所示 .

    在这个例子中,我停止传播到具有类“.subtable”的表内tr内的td内的任何元素(*)

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

    如果有人使用React有这个问题,这就是我解决它的方法 .

    SCSS:

    #loginBackdrop {
    position: absolute;
    width: 100% !important;
    height: 100% !important;
    top:0px;
    left:0px;
    z-index: 9; }
    
    #loginFrame {
    width: $iFrameWidth;
    height: $iFrameHeight;
    background-color: $mainColor;
    position: fixed;
    z-index: 10;
    top: 50%;
    left: 50%;
    margin-top: calc(-1 * #{$iFrameHeight} / 2);
    margin-left: calc(-1 * #{$iFrameWidth} / 2);
    border: solid 1px grey;
    border-radius: 20px;
    box-shadow: 0px 0px 90px #545454; }
    

    组件的render():

    render() {
        ...
        return (
            <div id='loginBackdrop' onClick={this.props.closeLogin}>
                <div id='loginFrame' onClick={(e)=>{e.preventDefault();e.stopPropagation()}}>
                 ... [modal content] ...
                </div>
            </div>
        )
    }
    

    通过为子模态(内容div)添加onClick函数,可以防止鼠标单击事件到达父元素的'closeLogin'函数 .

    这对我来说很有用,我可以用2个简单的div创建一个模态效果 .

  • 369
    var inner = document.querySelector("#inner");
    var outer = document.querySelector("#outer");
    inner.addEventListener('click',innerFunction);
    outer.addEventListener('click',outerFunction);
    
    function innerFunction(event){
      event.stopPropagation();
      console.log("Inner Functiuon");
    }
    
    function outerFunction(event){
      console.log("Outer Functiuon");
    }
    
    <!DOCTYPE html>
    <html>
    <head>
      <meta charset="utf-8">
      <meta name="viewport" content="width=device-width">
      <title>Pramod Kharade-Event with Outer and Inner Progration</title>
    </head>
    <body>
    <div id="outer" style="width:100px;height:100px;background-color:green;">
      <div id="inner" style="width:35px;height:35px;background-color:yellow;"></div>
    </div>
    </body>
    </html>
    
  • 3

    添加 a 如下:

    <a href="http://foo.com" onclick="return false;">....</a>
    

    return false; 来自 #clickable 的点击处理程序,如:

    $("#clickable").click(function() {
            var url = $("#clickable a").attr("href");
            window.location = url;
            return false;
       });
    
  • 0

    所有解决方案都很复杂,而且是jscript . 这是最简单的版本:

    var IsChildWindow=false;
    
    function ParentClick()
    {
        if(IsChildWindow==true)
        {
            IsChildWindow==false;
            return;
        }
        //do ur work here   
    }
    
    
    function ChildClick()
    {
        IsChildWindow=true;
        //Do ur work here    
    }
    
  • 0
    <a onclick="return false;" href="http://foo.com">I want to ignore my parent's onclick event.</a>
    

相关问题