Howto: div with onclick inside another div with on

2020-01-25 05:06发布

just a quick question. I'm having a problem with divs with onclick javascript within each other. When I click on the inner div it should only fire it's onclick javascript, but the outer div's javascript is also being fired. How can the user click on the inner div without firing the outer div's javascript?

<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条回答
2楼-- · 2020-01-25 05:42

return false; from the inner div's onclick function:

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

What you're dealing with is called event propagation.

查看更多
Melony?
3楼-- · 2020-01-25 05:42

One more way for webkit based browsers:

<div onclick="alert('inner'); event.stopPropagation;" ...
查看更多
干净又极端
4楼-- · 2020-01-25 05:42

Here is some more reference to help you in understanding javascript event bubbling.

查看更多
Anthone
5楼-- · 2020-01-25 05:56

Check out the info on event propagation here

In particular you'll want some code like this in your event handlers to stop events from propagating:

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();
}
查看更多
迷人小祖宗
6楼-- · 2020-01-25 05:58

This was very helpful, but it didn't work for me.

What i did is described here.

So I put a condition to the outer onclick event:

if( !event.isPropagationStopped() ) {
    window.location.href = url;
}
查看更多
叛逆
7楼-- · 2020-01-25 05:58

You can use

    $("divOrClassThatYouDontWantToPropagate").click(function( event ) {
      event.stopPropagation();
    });

查看更多
登录 后发表回答