Home > Web Front-end > JS Tutorial > body text

Example of using stopPropagation function to stop event propagation in JavaScript_javascript skills

WBOY
Release: 2016-05-16 16:38:26
Original
1656 people have browsed it

Events in JS default to bubbling, propagating upward layer by layer. You can stop the propagation of events in the DOM hierarchy through the stopPropagation() function. Such as the following example:

HTML code:

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>stopPropagation()使用 - 琼台博客</title>
</head>
<body>
<button>button</button>
</body>
</html>
[/code] 
没有加stopPropagation()
[code]
var button = document.getElementsByTagName('button')[0];
button.onclick=function(event){
  alert('button click');
};
 
document.body.onclick=function(event){
  alert('body click');
}
Copy after login

The DOM propagates upward layer by layer, so clicking the button button also propagates to the body layer, so the click on the body layer also responds. As a result, two warning boxes pop up, namely button and body.

Added stopPropagation()

var button = document.getElementsByTagName('button')[0];
button.onclick=function(event){
  alert('button click');
  // 停止DOM事件层次传播
  event.stopPropagation();
};
 
document.body.onclick=function(event){
  alert('body click');
}
Copy after login

The stopPropagation() is used in the button's click event processing function to stop the event propagation function. Therefore, after the warning box from the button click event pops up, it cannot be propagated to the body, and the body warning box will not pop up again. , the result is that the warning box is only discussed once.

When many children write JS, they often ignore the feature of DOM events propagating upward layer by layer, causing program abnormalities. If you need more in-depth knowledge, you can look for information about JS event bubbling.

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template