jQuery click() on a nested div

2019-04-29 13:20发布

The code can probably explain this better than I can:

<div class="wrapper">
    <div class="inner1"></div>
    <div class="inner2"></div>
</div>

<script>
$('div').click(function(){
    var class_name = $(this).attr('class');
    do_something(class_name);
});
</script>

When I click on the inner1 div, it runs the do_something() with both the inner1 div AND the wrapper.

With the site being built, nested divs are going to happen a lot. Is there a dynamic way to fix this issue and only run the top level div (in this case inner1)?

5条回答
我命由我不由天
2楼-- · 2019-04-29 13:45
<div class="wrapper">
    <div class="inner1"></div>
    <div class="inner2"></div>
</div>

<script>
$('div').click(function(ev){
    var class_name = $(this).attr('class');
    do_something(class_name);
    ev.stopPropagation();
});
</script>
查看更多
神经病院院长
3楼-- · 2019-04-29 13:46

You're selector is 'div' so on every single div that is clicked this will run. This includes wrapper, inner1, and inner2 in this example.

If you only want inner1 to fire off that function you're code will look like this:

$('.inner1').click(function(){
    var class_name = $(this).attr('class');
    do_something(class_name);
});
查看更多
Evening l夕情丶
4楼-- · 2019-04-29 13:49

You need to prevent the event bubbling. With jQuery, you would do this:

$('div').click(function(e)
{
    e.stopPropagation();

    // Other Stuff
});
查看更多
兄弟一词,经得起流年.
5楼-- · 2019-04-29 13:53

The event bubbles until you stop it with the stopPropagation method:

$('div').click(function(e){
  e.stopPropagation();
  var class_name = $(this).attr('class');
  do_something(class_name);
});
查看更多
放荡不羁爱自由
6楼-- · 2019-04-29 13:57

Use stopPropagation:

$('div').click(function(e){
    e.stopPropagation();
    var class_name = $(this).attr('class');
    do_something(class_name);
});

On the other hand: are you sure this is what you're trying to do? You might want to modify your selector ($('div')) to only target the DIV's you want.

查看更多
登录 后发表回答