admin管理员组

文章数量:1313750

I have a <div> element inside another <div>. I have an onClick event on the containing div but I want the inside div to ignore that onClick event, because I have a separate onClick event going on in that one. Here's some example code:

<div id='container' onClick='javascript:function1();'>
  outside of the inside div
  <div id='inside' onClick='javascript:function2();'>
    inside the inside div
  </div>
</div>

Just imagine the container is one big box, and the inside div is a smaller box inside of it. Basically the way the code works now, is every time I click "inside", it fires both the onClick even for "container" and "inside". I don't want that; I want each to have their own onClick event. Is this possible?

I have a <div> element inside another <div>. I have an onClick event on the containing div but I want the inside div to ignore that onClick event, because I have a separate onClick event going on in that one. Here's some example code:

<div id='container' onClick='javascript:function1();'>
  outside of the inside div
  <div id='inside' onClick='javascript:function2();'>
    inside the inside div
  </div>
</div>

Just imagine the container is one big box, and the inside div is a smaller box inside of it. Basically the way the code works now, is every time I click "inside", it fires both the onClick even for "container" and "inside". I don't want that; I want each to have their own onClick event. Is this possible?

Share Improve this question edited Jun 30, 2014 at 11:56 mandza 33010 silver badges24 bronze badges asked Jan 7, 2011 at 4:02 James NineJames Nine 2,61811 gold badges38 silver badges54 bronze badges 1
  • 1 This link can be useful: quirksmode/js/events_order.html – Jimmy Huang Commented Jan 7, 2011 at 4:08
Add a ment  | 

1 Answer 1

Reset to default 11

Inside function2() put return false which will prevent event bubling.

Since you have mentioned jquery in your tag you can remove the event handler from the HTML markup and put it inside document.ready

HTML

<div id='container'>
  outside of the inside div
  <div id='inside'>
    inside the inside div
  </div>
</div>

jQUery

$(function(){
    $("#container").click(function(){
        function1();
    });

    $("#inside").click(function(){
        function2();
        return false;
    });    
});

You can also use event.stopPropagation() instead of return false.

本文标签: javascriptHow to have two separate onClick events with one element inside anotherStack Overflow