jQuery on() and stopPropagation()

前端 未结 1 1357
南方客
南方客 2021-01-05 23:45

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. Bas

相关标签:
1条回答
  • 2021-01-06 00:27

    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.

    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.

    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.

    0 讨论(0)
提交回复
热议问题