JS block default event and JS block event bubbling sample share JS block Bubbling Event _ Basics

Source: Internet
Author: User

1. Event.preventdefault (); --The default event that blocks the element.
Note: A element of the click-Jump default event,

Default event for form elements such as Button,radio,

div element has no default event

Cases:

Copy Code code as follows:

<a href= "http://www.baidu.com" target= "_black" > Baidu </a>

Copy Code code as follows:

var samp = Document.getelementbytagname ("a");
Samp.addeventlistener ("click", Function (e) {e.preventdefault ()},false);

Explanation: Click on the link when the normal will occur jump, but now we have blocked its default event, that is, jump events, then will not jump to Baidu.


2. Event.stoppropagation (); --block element bubbling events

Note: Nested elements typically have bubbling events that can have some impact

Cases:

Copy Code code as follows:

<div id= "C1" onclick= "alert (1)" >
<div id= "C2" onlick= "alert (2)" >
<input type= "button" Id= "C3" Value= "click" onclick= "alert (3)" >
</div>
</div>

Click button here, the browser will pop up 3,2,1, originally just want to bind the event on the button, but inadvertently triggered its two parent events, here we just did a simple test, imagine if in the project development, A button and his parent bind important events at the same time, and the result can be disastrous. The way to do this is to block bubbling events.

Registers the Click event with input and blocks its bubbling events

Copy Code code as follows:

document.getElementById (' C3 '). AddEventListener (' click ', Function (e) {e.stoppropagation ()},false);

Ok!!! Had

PS: Here again for you to recommend a JS event on the online query tool, summed up JS commonly used event types and function functions:

JavaScript event and Feature description encyclopedia:

Http://tools.jb51.net/table/javascript_event

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.