I would like to add two events to my item.
Document for a "background": $ (document) .click (function () {do ()});
One for the divs in the document: $ ("div") .click (function () {do2 ()});
The problem is that when I click on div
, both functions, ,
and do2
Is called.
How can I say to call do ()
, when I click on no element?
Thank you for your help,
J.
The post you are viewing here is event promotion or event bubbling.
The "handling" of the "modern" browsers (which has the most libraries in the model) hooks up the document tree. This means that if you have the html document structure like << p>
And if someone clicks on Foo, the following is the event material
- & lt; Li & gt; One click receives event
- & lt; Ul & gt; One click receives event
- & lt; Div & gt; One click receives event
- & lt; Body & gt; One click receives event
What's going on with you
First of all, as many people have suggested that if your event handler returns false , The promotion of the event will be closed on the element that has been clicked. (This is how jQuery handles, each library has a different perspective)
$ (document) .ready (function () {// hookup events for the whole body of the document $ (' Body 'Bind (' click ', function (e) bind (' click ', function (e) {// do body stuff clicked}); // false to prevent our divs hookup, bubbling $ (' div ') Returning. {// Dave content replaces false; // stop event presentation};});
One second, some will argue better, approach delegation is to use delegation Ive In terms of TD delegation, Javascript and DOM, where you attach the same event handler to an external element (in this case the body), and then take a special action based on the element that is originally clicked.
Something like this.
$ (document) .ready (function () {// event delegate $ ('body'). Bind ('click', function ( E) {var originalElement = e.srcElement; if (original element) {original element = eorgan target}; if ($ (basic element) .is ('div')) {console.log ("A div! ") Else} ($ (original Alem Ents) .is ('div # inside')) {console.log ("a specific div!");} And {console.log ("some more!");}});});
Its profit is two times. First of all, you can centralize all of your event handling codes in one place in your code. The second (more important in my mind) is enclosing a single event handler that consumes very little browser memory and sets you up for better performance.
Comments
Post a Comment