Js blocking default events and js blocking events bubble examples share js blocking events _ basic knowledge

Source: Internet
Author: User
Nested div elements. If the parent and child elements are bound to some events, the parent element event may be triggered when you click the child element at the inmost layer, the following is an example of js blocking default events and js blocking event bubbling. For more information, see section 1. event. preventDefault (); -- blocks default events of elements.
Note: The default event for clicking to jump to element,

Default events for button, radio, and other form elements,

No Default event for the p element


The Code is as follows:


The Code is as follows:

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

Explanation: When you click a link, a jump will normally occur, but now we have blocked its default event, that is, the jump event, so it will not jump to Baidu.

2. event. stopPropagation (); -- block the event of element bubbling

Note: Nested elements generally have bubble events, which may have some impact.


The Code is as follows:

When you click the button, the browser will pop up 3, 2, 1. Originally, only the events bound to the button were triggered, but the events at the two parent level were accidentally triggered, here we just did a simple test. Imagine if a button is bound to a very important event at the same time with its parent in project development, the results would be miserable. At this time, the solution is to stop the bubble event.

Register a click event for input and block its bubble events.

The Code is as follows:

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

OK !!! Now

Related Article

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.