javascript - Two click events. The large DIV contains the small DIV. If you click the small DIV, the large one will also be triggered. How to deal with it?
某草草
某草草 2017-05-27 17:44:35
0
8
1355

Two click events, the big p contains the small p, if you click on the small p, the big one will also be triggered. How to deal with it?
As shown in the figure, if you click on the click inside the small p, the big p will also be triggered. Now you only want to click on the small p and only the small click event will be triggered. How to deal with it?


Now

某草草
某草草

reply all(8)
伊谢尔伦

stopPropagation()

给我你的怀抱

Trigger a certain type of event on an object (such as click onclick event). If this object defines a handler for this event, then this event will call this handler. If this event handler is not defined or the event returns true, then this event will propagate to the parent object of this object, from inside to outside, until it is processed (all similar events of the parent object will be activated), or it reaches the top level of the object hierarchy, that is The document object (in some browsers it is window), is called event bubbling.

//阻止事件冒泡函数
function stopBubble(e)
{
    if (e && e.stopPropagation)
        e.stopPropagation()
    else
        window.event.cancelBubble=true
}
迷茫

It is the bubbling (capture) event of JS

Solutions like this are quite simple

$('.p1').on('click', function(event) {
    event.preventDefault();
    if ($(event.target).is('.p2')) {
        alert('click 2')
    }else{
        alert('click 1')
    }
});
Ty80

js bubbling, just cancel the bubbling
Use event delegation and this problem will not occur

为情所困

Come to me if you don’t understand after reading these two articles:

http://javascript.info/bubbli...
https://stackoverflow.com/que...

阿神

I think of two solutions:
1. Prevent events from bubbling.
Event bubbling is executed step by step from the inner child element to the outer parent element. When executing the click event of the child element, the bubbling blocking event needs to be called, so that the event cannot be passed to the upper layer to execute the upper layer event.
2. Execute different events based on the element that caused the click.
When the clicked element is caused by a child element, event A is executed. If it is not a child element, event B is executed.

淡淡烟草味

Just stop bubbling. For more information about the incident, please see here /a/11...

曾经蜡笔没有小新

According to normal practice, it will not be triggered like this. I really want to know what selector you use to bind the click event. It would be better if you post your click code and the html code of your p

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template