jQuery click()嵌套div [英] jQuery click() on a nested div
本文介绍了jQuery click()嵌套div的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
代码可能会比我更好地解释这一点:
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>
当我点击 inner1
它使用 inner1
div和 wrapper $ c>运行
do_something()
$ c>。
When I click on the inner1
div, it runs the do_something()
with both the inner1
div AND the wrapper
.
在构建网站时,嵌套的div会发生很多。是否有动态的方法来解决这个问题,只运行顶级div(在这种情况下 inner1
)?
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
)?
推荐答案
使用 stopPropagation
:
$('div').click(function(e){
e.stopPropagation();
var class_name = $(this).attr('class');
do_something(class_name);
});
另一方面:你想做什么?您可能想要修改选择器( $('div')
),只定位您想要的DIV。
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.
这篇关于jQuery click()嵌套div的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文