jquery handles event bubbling

Source: Internet
Author: User

<div class= "foo" ><!--lang:html--><span class= "Bar" ><!--lang:html--><a href= "/http/ www.example.cm/"><!--lang:html--></a><!--lang:html--></span><!--lang:html-->& lt;p><!--lang:html--></p><!--lang:html--></div>

But we clicked on the <a>, three elements that were under the user's mouse pointer, and

element is irrelevant to this interaction.

Event capture is first handed to the outermost element, and then to a layer of

The other opposite strategy is that the most specific elements get a chance to respond before bubbling to more general elements.

The solution:

Example:

<div id= "Container" ><!--lang:html--  <div id= "switcher" ><!--lang:html-

1. Event Target

$ (' #switcher '). Click (Function (event) {
if (Event.target = = this) {
$ (' #switcher. Button '). Toggleclass (' hidden ');
}
})

Make sure that the element you clicked is

, not the outside element

2, the following method, although in cross-browser can not be used safely, as long as the use of jquery to register all events can be used with confidence.
$ (document). Ready (function () {
$ (' #switcher. Button '). Click (Function (event) {

$ (' body '). Removeclass (); if (this.id = = ' Switcher-narrow ') {  $ (' body '). addclass (' narrow ');} else if (this.id = = ' Switcher-large ') {  $ (' Body '). addclass (' large '); }

$ (' #switcher. Button '). Removeclass (' selected ');

$ (this). AddClass (' selected '); Event.stoppropagation ();   Avoid all other DOM elements in response to this event, so that the clicked event will only be handled by the button.

});
});

The default is bubbling, if cancel bubbling can take:
Cancelbubble=true
or jquery's event.stoppropagation ();

jquery handles 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.