如何停止将事件从父级div传播到子级div [英] How to stop propagating event from parent div to child div

查看:168
本文介绍了如何停止将事件从父级div传播到子级div的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在我的html中停止从父级div传播到子级div的事件.这是我想做的简单代码:

I want to stop propagate event from parent div to child div in my html. Here a simple code what I'm trying to do:

<div>
  <div id='categoryList'>
    <div class='listed-category'>
      <span>some content</span>
      <a id='close'>x</a> //"a" is used to remove the div
    </div>
  </div>
</div>
<div id='dropdown'>
</div>

在上面的代码中,如果我单击<div id='categoryList'>,则<div id='dropdown'>将通过以下代码上下滑动.

In the above code if I click on <div id='categoryList'> the <div id='dropdown'> will slide-up and down by bellow code.

$(document).ready(function () {

    $('#categoryList').click(function (event) {
        event.preventDefault();
        event.stopPropagation();
        if ($('#dropdown').is(":visible")) {
            $('#dropdown').slideUp(400);
        }
        else {
            $('#dropdown').slideDown(400);
        }
    });
})

但是,当我单击子级<div class='listed-category'>时,将执行上述JavaScript,并且<div id='dropdown'>会上下滑动.如何停止呢?但是我希望能够单击<a id='close'>删除子级div

But when I click on the child <div class='listed-category'> the above JavaScript executes and the <div id='dropdown'> is sliding up and down. How to stop this? Yet I want to be able to click on <a id='close'> to remove the child div

推荐答案

检查目标是否有匹配的单击对象.在点击事件处理程序的开头尝试使用此代码.

Check target for match clicked object. Try this code in beginning of click event handler.

if( event.target !== this ) {
       return;
}
//...do stuff.. 

这篇关于如何停止将事件从父级div传播到子级div的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆