The application scenario of event bubbling and event capture--event agent/event delegate

Source: Internet
Author: User

Use the event agent to bind the click event for all a tags in the page.

Document.addeventlistener ("click", Function (e) {
	if (E.target.nodename = = "a")
		Console.log ("a");
FALSE);

Problem: If the a tag still has span, IMG and other elements, in the above code, click Span, IMG and other elements can not trigger the Click event.

Reason: When you click on other elements such as span, IMG, and so on, e.target points to the element that triggers the Click event (Span, IMG, and other elements) instead of a label.

Workaround: Start with the element that triggers the Click event, and look up until you find the A label.

Document.addeventlistener ("click", Function (e) {
	var node = e.target;
	while (Node.parentNode.nodeName!= "Body") {
		if (Node.nodename = = "a") {
			console.log ("a");
			break;
		node = Node.parentnode;
	}
}, False);

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.