How do I manually trigger a delegated event with jQuery?

后端 未结 5 496
清酒与你
清酒与你 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 04:58

    We can pass an additional event configuration to jQuery's $.Event() as the second argument. More information here.

    $('#click-me').on('click', function(evt){
      $(document).trigger($.Event('custom-click', {target: evt.currentTarget}));
    });
    
    $(document).on('custom-click', '#click-me', function(evt){
      alert(`${evt.type} was triggered on button with ${evt.target.id} id.`);
    })
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    
    
    <button id="click-me">Click Me</button>

    Good Luck...

    0 讨论(0)
  • 2020-12-08 05:08

    As a complementary to @Prinzhorn's answer, it may be useful to have this JQuery function:

    (function( $ ){
        $.fn.triggerParent = function (eventName, parent) {
            this.each(function() {
                var event = jQuery.Event(eventName);
                event.target = this;
                $(parent).trigger(event);
            });
        };
    })( jQuery );
    
    0 讨论(0)
  • 2020-12-08 05:10

    You could create an Event object manually and set the target property accordingly to trick jQuery into thinking the event bubbled up.

    var c = $('#container');
    
    c.on('click', '[type=button]', function(e) {
        $(e.delegateTarget).find('span').text($(this).val());
    });
    
    var event = jQuery.Event('click');
    event.target = c.find('[type=button]')[0];
    
    c.trigger(event);
    

    http://jsfiddle.net/PCLFx/

    0 讨论(0)
  • 2020-12-08 05:18

    I know, this question is ancient but as I was stumbling over it while looking for an answer to another problem I thought I might as well share my slightly simpler approach here.

    The idea is to simply create the event on the desired target element directly: $(target_selector).trigger(event_type) or - even shorter for standard events like "click" - do $(target_selector).click(), see my little fiddle below:

    $(function(){
     $('.container').on('click','button',function(){
      console.log('delegated click on '+$(this).text());
      return false;
     });
     $('#other').click(e=>$('.container button').trigger('click'));
     $('#clickone').click(e=>$('.container .one').click());
    });
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <form class="container">
    <button type="submit" class="one">click 1</button> and another chance to click here on <button class="two">click 2</button>.
    </form><br>
    <div id="other">Trigger clicks on both buttons here!</div><br>
    <div id="clickone">Trigger a click on button "one" only.</div>

    0 讨论(0)
  • 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.

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