Direct vs. Delegated - jQuery .on()

前端 未结 5 1505
鱼传尺愫
鱼传尺愫 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:35

    Case 1 (direct):

    $("div#target span.green").on("click", function() {...});
    

    == Hey! I want every span.green inside div#target to listen up: when you get clicked on, do X.

    Case 2 (delegated):

    $("div#target").on("click", "span.green", function() {...});
    

    == Hey, div#target! When any of your child elements which are "span.green" get clicked, do X with them.

    In other words...

    In case 1, each of those spans has been individually given instructions. If new spans get created, they won't have heard the instruction and won't respond to clicks. Each span is directly responsible for its own events.

    In case 2, only the container has been given the instruction; it is responsible for noticing clicks on behalf of its child elements. The work of catching events has been delegated. This also means that the instruction will be carried out for child elements that are created in future.

提交回复
热议问题