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

js prevents default events and js prevents event bubbling examples to share js prevents bubbling events_basic knowledge

WBOY
Release: 2016-05-16 17:02:11
Original
1403 people have browsed it

1. event.preventDefault(); -- Prevent the default event of the element.
Note: The default event for click jump of element a,

Default events for button, radio and other form elements,

div element has no default event

Example:

Copy code The code is as follows:

Copy code The code is as follows:

var samp = document.getElementByTagName("a");
samp.addEventListener("click",function(e){e.preventDefault()},false);

Explanation: When you click on a link, a jump will occur under normal circumstances, but now we have blocked its default event, which is the jump event, and it will not jump to Baidu.


2. event.stopPropagation(); -- Prevent element bubbling events

Note: Nested elements generally have bubbling events, which will have certain effects

Example:

Copy code The code is as follows:






When the button is clicked here, the browser will pop up 3, 2, and 1 successively. Originally, we only wanted the event bound to the button to occur, but inadvertently triggered events on its two parents. Here we I just did a simple test. Imagine if during project development, a button and its parent were bound to important events at the same time, the results would be disastrous. The solution at this time is to prevent bubbling events.

Register the click event for the input and prevent its bubbling event

Copy the code The code is as follows:

document.getElementById('c3').addEventListener('click',function(e){e.stopPropagation()},false);

OK! ! !

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
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!