JS prevents the bubbling of events-Kaiqisan

ヤッハロー、Kaiqisanすうう、一つふつうの学生プログラマである. In the past, one thing has always troubled me, that is, when I try to trigger the click event inside the element, the click event of the external element is always triggered. , I can't stop it, until today, I understand the incident bubbling, and I have a great understanding.

Short answer

function fun2(e) {
    
    
	e = e || window.event	// window.event 用于兼容ie
	window.event ? e.cancelBubble = true : e.stopPropagation()
    console.log('ok1')
}

Detailed

for example

<div class="demo" onclick="fun1()">
	<div class="inner-demo" onclick="fun2(event)">dddddddddddd</div>
</div>
function fun1() {
    
    
	console.log('ok1')
}

function fun2(e) {
    
    
	console.log('ok2')
}

Each time you click the event fun2 of the inner-demo of the inner element area, the demo event fun1 will be triggered.

This is because the event bubbling- after the internal event is triggered, it will trigger the same event of its parent element , and then trigger the parent element of the parent element, and so on, until the outermost The window stops. Take the above triggering internal element inner-demo as an example. After printing the event object of the event, check its path property, and you can see the path of the bubbling event

function fun2(e) {
    
    
	console.log(e.path)
}

Then the fun2 method is triggered, followed by the fun1 method. Since there is no click event at the higher level, the chain of events generated by this bubbling ends here.

The solution is of course to prevent bubbling from occurring

function fun2(e) {
    
    
	e = e || window.event	// window.event 用于兼容ie
	window.event ? e.cancelBubble = true : e.stopPropagation()
    console.log('ok1')
}

This will prevent bubbling, and internal click events will not be distributed to the outside. This element is "isolated".

to sum up

Event bubbling is still a very important method, it is recommended to memorize it.

Guess you like

Origin blog.csdn.net/qq_33933205/article/details/108391030