triggerHandler vs. trigger in jQuery

后端 未结 4 656
暖寄归人
暖寄归人 2020-12-01 06:33

Out of curiosity -- what is the purpose of / use cases for jQuery\'s triggerHandler? As far as I can tell, the only \"real\" differences between trigger

4条回答
  •  鱼传尺愫
    2020-12-01 06:46

    Difference 1: you can call all elements matched by the JQuery object using trigger.

    //Example1 for trigger. All 3 button click events are fired when used trigger. //Try Replacing trigger method with triggerHandler(). You will see only the first button element event handler will fire .

    
    
    
    
    $("#button1").on("click", function(){
    alert("button1 clicked");
    });
    $("#button2").on("click", function(){
    alert("button2 clicked");
    });
    $("#button3").on("click", function(){
    alert("button3 clicked");
    });
    

    //substitute trigger with triggerHandler to see the difference

    $("#button1, #button2, #button3").trigger("click");
    

    Difference 2: when using triggerHandler() for an element event, the native event will not be called for that element. trigger() will work fine.

    //Example:

    //substitute trigger with triggerHandler to see the difference

     
      
    
    $("#button1").on("click", function(){
     $("#button2").trigger('click');
    
    });
    
    $("#button3").on("click", function(){
    var value = $("#button2").triggerHandler('click');
        alert('my value:'+ value)
    });
    
    $("#button2").on('click', function(){
    alert("button2 clicked");
    
    });
    

    Difference 3: trigger() return Jquery object whereas triggerHandler() return the last handle value or If no handlers are triggered, it returns undefined

    //Example3

    
    
    
    
    
    $("#button1").on("click", function(){
    var myValue = $("#button2").trigger('click');
        alert(myValue);
    });
    
    $("#button3").on("click", function(){
    var value = $("#button2").triggerHandler('click');
        alert('my value:'+ value)
    });
    
    $("#button2").on('click', function(){
    alert("button2 clicked");
        return true;
    });
    

    Other difference is

    Events triggered with triggerHandler() do not bubble up the DOM hierarchy; if they are not handled by the target element directly, they do nothing.

提交回复
热议问题