简体   繁体   中英

How to add a click method inside of element with click method?

Suppose I have:

   <div id="outer" onclick="thingsHappen()">
      <div id="inner"></div>
   </div>

When I click on outer or inner div, thingsHappen() is executed. That is obvious.

Now I have got a need to define a different method for the inner div. For example

$("#inner").click(function() {
    doThings();
});

When I click on inner both thingsHappen() and doThings() executes. How do I execute doThings() when I click on inner div without executing thingsHappen()?

I tried to unbind click method from #inner, but it did not work. PS. I cannot change the structure of HTML.

Stop the propagation of the event:

$("#inner").click(function(e) {
    doThings();
    e.stopPropagation();
});

Example: http://jsfiddle.net/QNt76/

JavaScript events bubble up the DOM tree unless you stop them from propagating. This is what was causing the parent event handler to get notified.

You want Event.stopPropagation() :

$("#inner").click(function(e) {
    doThings();
    e.stopPropagation();
});
$("#inner").click(function(e) {
    e.stopPropagation();
    doThings();
});​

You have to stop the propagation to the Document Tree:

$("#inner").click(function(event) {
    doThings();
    event.stopPropagation();
});

See: http://api.jquery.com/event.stopPropagation/

Prevents the event from bubbling up the DOM tree, preventing any parent handlers from being notified of the event.

Events pertaining to a child element bubble up to parent elements in the DOM unless propagation is stopped like so:

$("#inner").click(function(event) {
    doThings();
    event.stopPropagation();
});

Here is a good read on capturing/bubbling and Javascript events. http://www.quirksmode.org/js/events_order.html

What you are trying to do is stop the event (click) from "bubbling" up. In this case, you would want to stop the propagation of the event in the bubbling phase. If you are using jquery, you can use this function:

HTML

<div id="outer" onclick="thingsHappenOuter()"> 
    <div id="inner">
    </div> 
</div>

JS

$("#inner").click(function(event) {       
    event.stopPropagation();
    // do something     
});

SEE: http://api.jquery.com/event.stopPropagation/ for more information.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM