Direct vs. Delegated - jQuery .on()

前端 未结 5 1489
鱼传尺愫
鱼传尺愫 2020-11-21 05:11

I am trying to understand this particular difference between the direct and delegated event handlers using the jQuery .on() method. Specifically, the last

5条回答
  •  渐次进展
    2020-11-21 05:30

    Tangential to the OP, but the concept that helped me unravel confusion with this feature is that the bound elements must be parents of the selected elements.

    • Bound refers to what is left of the .on.
    • Selected refers to the 2nd argument of .on().

    Delegation does not work like .find(), selecting a subset of the bound elements. The selector only applies to strict child elements.

    $("span.green").on("click", ...
    

    is very different from

    $("span").on("click", ".green", ...
    

    In particular, to gain the advantages @N3dst4 hints at with "elements that are created in future" the bound element must be a permanent parent. Then the selected children can come and go.

    EDIT

    Checklist of why delegated .on doesn't work

    Tricky reasons why $('.bound').on('event', '.selected', some_function) may not work:

    1. Bound element is not permanent. It was created after calling .on()
    2. Selected element is not a proper child of a bound element. It's the same element.
    3. Selected element prevented bubbling of an event to the bound element by calling .stopPropagation().

    (Omitting less tricky reasons, such as a misspelled selector.)

提交回复
热议问题