How do I manually trigger a delegated event with jQuery?

后端 未结 5 510
清酒与你
清酒与你 2020-12-08 04:27

Is there a way with jQuery to manually trigger an delegated event handler?

Take following example code:

5条回答
  •  时光取名叫无心
    2020-12-08 05:19

    Selectors in the .on() method are optional.
    When you write:

      $('.container')
        .on('click', '[type=button]', function(e) {
          $(e.delegateTarget).find('.output').text($(this).val());
        })
        .find('[type=button]').triggerHandler('click');​
    

    You are telling the event handler to listen only to the button click inside the container.
    $(e.delegateTarget) is just a reference to the outer container.

    I've updated your fiddle to echo this.

    This is a quote from the API:

    When a selector is provided, the event handler is referred to as delegated. The handler is not called when the event occurs directly on the bound element, but only for descendants (inner elements) that match the selector. jQuery bubbles the event from the event target up to the element where the handler is attached (i.e., innermost to outermost element) and runs the handler for any elements along that path matching the selector.

提交回复
热议问题