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 06:00

Just add this code :

window.event.stopPropagation();
查看更多
Fickle 薄情
3楼-- · 2020-01-25 06:04

This worked for me in Jquery:

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

This way, if the current target is not the same as the outer div, it will do nothing. You can implement normal functions on the child elements.

查看更多
Anthone
4楼-- · 2020-01-25 06:05

Basically there are two event models in javascript. Event capturing and Event bubbling. In event bubbling, if you click on inside div, the inside div click event fired first and then the outer div click fired. while in event capturing, first the outer div event fired and than the inner div event fired. To stop event propagation, use this code in your click method.

   if (!e) var e = window.event;
    e.cancelBubble = true;
    if (e.stopPropagation) e.stopPropagation();
查看更多
做个烂人
5楼-- · 2020-01-25 06:06

This is a case of event bubbling.

You can use

e.cancelBubble = true; //IE

and

e.stopPropagation(); //FF
查看更多
ゆ 、 Hurt°
6楼-- · 2020-01-25 06:08

you have two 'div' and three '/div'.

查看更多
登录 后发表回答