开发者

How to have two separate onClick events with one element inside another?

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 pos开发者_开发问答sible?


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜