jQuery on()和stopPropagation() [英] jQuery on() and stopPropagation()

查看:97
本文介绍了jQuery on()和stopPropagation()的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个从左侧滑入的侧窗格,使用get()动态添加内容.我希望窗格外的所有单击都可以通过触发功能来使其关闭.根据我阅读的其他问题,我想到了以下代码.

I have a side pane that slides in from the left, adding content dynamically with get(). I want all clicks outside the pane to cause it to close by triggering a function. Based on other questions I read, I came up with the following code.

$('html').click(function() {
    if (side_showing) {
        close_side();
    }
});

$(document).on("click", "#side", function(event) {  
    event.stopPropagation();
});

我似乎无法使其正常运行.我知道on()函数正在被触发,但是event.stopPropagation似乎没有被触发.有提示吗?

I can't seem to make it work. I know that the on() function is being triggered, but event.stopPropagation doesn't seem to be. Any tips?

推荐答案

您不能将stopPropagation()与委托事件处理一起使用(事件处理程序位于父对象上).

You can't use stopPropagation() with delegated event handling (where the event handler is on a parent).

这是因为事件传播首先使委托事件处理工作,因此,在调用事件处理程序时,事件已经传播.

That's because it is event propagation that makes delegated event handling work in the first place so by the time your event handler gets called, the event has already propagated.

代码中发生的事情的顺序是:事件传播到文档对象,然后调用事件处理程序.因此,当您调用event.stopPropagation()时,它不会执行任何操作,因为该事件已经传播.

The order of things happening in your code is: event propagation up to the document object, then your event handler gets called. So, when you call event.stopPropagation() it doesn't do anything because the event has already propagated.

如果需要防止父对象获取事件传播,则不能使用委托事件处理.您将必须直接将事件处理程序分配给对象本身,以便可以在事件传播之前对其进行拦截.如果这些是动态创建的对象,则必须在创建它们后立即为其分配事件处理程序.

If you need to keep parent objects from getting event propagation, then you can't use delegated event handling. You will have to assign event handlers directly to the objects themselves so you can intercept the event BEFORE it propagates. If these are dynamically created objects, then you will have to assign event handlers to them right after they are created.

我唯一知道的另一种解决方案是将事件处理程序放置在您不想看到这些事件的父对象上,并确保如果这些事件处理程序起源于您的#side对象,则忽略这些事件.

The only other solution I know of is to put event handlers on the parent objects that you don't want to see these events and make sure those event handlers ignore the events if they originate on your #side object.

这篇关于jQuery on()和stopPropagation()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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