事件传播问题 [英] Event propagation issue

查看:65
本文介绍了事件传播问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一系列点击事件,这些事件导致我出现了一些传播问题.该容器的数据是通过ajax加载的,因此是单击主体.这是我的代码:

I have a series of click events which are causing me some propagation issues. The data for this container is loaded in via ajax hence the body on click method. Here's the code I have:

$(function () {
    $("body").on("click","#top-div",function(){
        console.log("top event");
    });

    $("body").on("click","#middle-div",function(e){
        e.stopPropagation();
    });

    $("body").on("click","#bottom-div",function(){
        console.log("bottom event");
    });
  });

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="top-div">
  top
    <div id="middle-div">
      middle
        <div id="bottom-div">
          bottom
        </div>
    </div>
</div>

顶部div发生了一个事件,中间一个事件无需继承,因此stopPropagation().但是,最下面的事件需要有一个自己的事件,但是中间的stopPropagation()会阻止它执行该事件(如果我删除停止传播,则最下面的事件会触发,但碰巧最上面的事件也会触发)

The top div has an event which the middle one needs to not inherit hence the stopPropagation(). However the bottom one needs to have an event of its own but the stopPropagation() from the middle one is stopping it from executing the event (if I remove the stop propagation the bottom event triggers but coincidentally so does the top)

如何解决这个冒泡的问题?

How can I get around this bubbling issue?

推荐答案

您想发生的事情是,仅当传播起源于中间div时才停止传播.如果它起源于底部div,则您希望事件一直冒泡至顶部.

I think what you want to happen is that the propagation is only stopped if it originated from the middle div; if it originated from the bottom div you want the event to bubble all the way to the top.

您需要有条件地致电stopPropagation.如果该事件不是在#bottom-div上或内部发起的,则要对其进行调用.您可以使用 closest :

You need to call stopPropagation conditionally. If the event did not originate on or inside #bottom-div, you want to call it. You can test for this using closest:

if (!$(e.target).closest('#bottom-div').length) {
    e.stopPropagation();
}

最好使用closest,而不是直接测试元素的id,因为使用closest,即使有其他元素(aem (例如)在各种div中.

It is better to use closest for this, rather than testing the element's id directly, because with closest it will continue to work as expected even if there are other elements (a or em, for example) within the various divs.

$(function () {
    $("body").on("click","#top-div",function(){
        console.log("top event");
    });

    $("body").on("click","#middle-div",function(e){
        if (!$(e.target).closest('#bottom-div').length) {
            e.stopPropagation();
        }
    });

    $("body").on("click","#bottom-div",function(){
        console.log("bottom event");
    });
  });

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="top-div">
  top
    <div id="middle-div">
      middle
        <div id="bottom-div">
          bottom
        </div>
    </div>
</div>

这篇关于事件传播问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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