代码之家  ›  专栏  ›  技术社区  ›  Daniel Brink

Howto:div with onclick在另一个div with onclick javascript中

  •  42
  • Daniel Brink  · 技术社区  · 15 年前

    <html>
    <body>
    <div onclick="alert('outer');" style="width:300px;height:300px;background-color:green;padding:5px;">outer div
        <div onclick="alert('inner');"  style="width:200px;height:200px;background-color:white;" />inner div</div>
    </div>
    </div>
    </body>
    </html>
    
    11 回复  |  直到 15 年前
        1
  •  109
  •   Adeel    15 年前

    javascript中基本上有两个事件模型。 事件捕获 . 在事件冒泡中,如果单击inside div,则先触发inside div click事件,然后触发outer div click事件。在事件捕获中,首先触发外部div事件,然后触发内部div事件。要停止事件传播,请在click方法中使用此代码。

       if (!e) var e = window.event;
        e.cancelBubble = true;
        if (e.stopPropagation) e.stopPropagation();
    
        2
  •  23
  •   Tim Goodman    15 年前

    查看有关事件传播的信息 here

    特别是,您需要在事件处理程序中使用类似这样的代码来阻止事件传播:

    function myClickHandler(e)
    {
        // Here you'll do whatever you want to happen when they click
    
        // now this part stops the click from propagating
        if (!e) var e = window.event;
        e.cancelBubble = true;
        if (e.stopPropagation) e.stopPropagation();
    }
    
        3
  •  6
  •   user3438083    11 年前

    只需添加以下代码:

    window.event.stopPropagation();
    
        4
  •  5
  •   Tatu Ulmanen    15 年前

    return false; 从内部div的onclick函数:

    <div onclick="alert('inner'); return false;" ...
    

    event propagation .

        5
  •  5
  •   rahul    15 年前

    这是一个事件冒泡的例子。

    e.cancelBubble = true; //IE
    

    e.stopPropagation(); //FF
    
        6
  •  3
  •   Juliano Moraes    13 年前

    基于webkit的浏览器还有一种方法:

    <div onclick="alert('inner'); event.stopPropagation;" ...
    
        7
  •  0
  •   Ben    15 年前
        8
  •  0
  •   freddie    14 年前

    你有两个'div'和三个'/div'。

        9
  •  0
  •   Community CDub    8 年前

    这很有帮助,但对我没用。

    我所做的一切都被描述出来了 here .

    所以我在外面加了个条件 onclick 事件:

    if( !event.isPropagationStopped() ) {
        window.location.href = url;
    }
    
        10
  •  0
  •   AngelQuesada    10 年前

    你可以用

        $("divOrClassThatYouDontWantToPropagate").click(function( event ) {
          event.stopPropagation();
        });
        11
  •  0
  •   Ramtin    7 年前

    这在Jquery中对我很有用:

    $('#outer_element').click(function(event) {
        if(event.target !== event.currentTarget) return;
        alert("Outer element is clicked")                       
    });