Clicking on one button to trigger click event on another

后端 未结 3 655
被撕碎了的回忆
被撕碎了的回忆 2021-01-18 01:46

I want to click on button 2 to trigger a click event on button 1.

However, when I try the following, nothing happens when clicking on #2: no alert for #1 or #2.

3条回答
  •  -上瘾入骨i
    2021-01-18 02:10

    To properly trigger a delegated event you have to create an event object and pass it to trigger()

    $('#container').on( "click", '#button-2', function(e){
        var event = jQuery.Event(e.type);
        event.target = $('#button-1').get(0);
    
        $('#container').trigger(event);
    });
    

    FIDDLE

    That way you're actually triggering the event on the element it was bound to, passing the selector the delegated event handler will filter on as the event.target, so it will fire just as it would if the element was actually clicked.

    Or you could use the original event if you change the event.target

    $('#container').on( "click", '#button-1', function(e){
        alert('CLICKED 1');
    });
    
    $('#container').on( "click", '#button-2', function(e){
        e.target = $('#button-1').get(0);
        $('#container').trigger(e);
    });
    

提交回复
热议问题