JS Event bubbling

Source: Internet
Author: User

There are two very important features in the Javasciprt event: event bubbling and the target element.


Event bubbling: When an event on an element is triggered, such as a mouse click on a button, the same event will be triggered in all ancestor elements of that element. This process is known as event bubbling, which bubbles to the top of the DOM tree from the beginning of the original element.


Target element: The target element of any event is the first element, in our example, the label. With the event agent, we can add an event handler to an element, wait for an event to bubble up from its child element, and be able to easily tell which element the event started from.

Bubbling and capturing of events
The capture is from the ancestor element to the subordinate element, bubbling from the subordinate element to the ancestor element.

The following program simulates event bubbling:

<%@ page language= "java" import= "java.util.*" pageencoding= "utf-8"%><%string path = Request.getcontextpath () ; String basepath = request.getscheme () + "://" +request.getservername () + ":" +request.getserverport () +path+ "/";%> <! DOCTYPE HTML PUBLIC "-//w3c//dtd HTML 4.01 transitional//en" >

  

To access this page, click Label to view the console output:

You can see the order in which the event fires after clicking the label:

1. Trigger the label's onclick event;

2. Trigger the onclick event of input;

A 3.input Click event causes event bubbling to trigger the outer label Click event.

Workaround:

If you click on an element and don't want the event to propagate, you can use the following methods

<%@ page language= "java" import= "java.util.*" pageencoding= "utf-8"%><%string path = Request.getcontextpath () ; String basepath = request.getscheme () + "://" +request.getservername () + ":" +request.getserverport () +path+ "/";%> <! DOCTYPE HTML PUBLIC "-//w3c//dtd HTML 4.01 transitional//en" >

  

This only invokes the label's Click event and is called only once.

JS Event bubbling

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.