嵌套 div 上的 jQuery click()
该代码可能比我能更好地解释这一点:
<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
div 时,它会使用 inner1
运行 do_something()
div 和包装器
。
随着网站的建设,嵌套 div 将会发生很多。是否有一种动态方法来解决此问题并仅运行顶级 div(在本例中为 inner1
)?
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
)?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
使用
stopPropagation
:另一方面:您确定这是你想做什么?您可能需要修改选择器 (
$('div')
) 以仅定位您想要的 DIV。Use
stopPropagation
: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,你可以这样做:
You need to prevent the event bubbling. With jQuery, you would do this:
您的选择器是“div”,因此在单击的每个 div 上都会运行。在此示例中,这包括wrapper、inner1 和inner2。
如果您只想 inner1 触发该函数,您的代码将如下所示:
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:
事件会一直冒泡,直到您使用
stopPropagation
方法停止它为止:The event bubbles until you stop it with the
stopPropagation
method: