Use jQuery .trigger to call a custom function that returns a value

后端 未结 4 1400
有刺的猬
有刺的猬 2021-02-14 04:34

Is there any way using jQuery\'s .bind() and .trigger() calls to execute a user defined function (ex: save ()) and act upon the return from the method? For example:

<         


        
4条回答
  •  轮回少年
    2021-02-14 04:41

    Check out triggerHandler(), which in many other ways acts like trigger() but will allow you to return a value.

    From the docs:

    The .triggerHandler() method behaves similarly to .trigger(), with the following exceptions:

    • The .triggerHandler() method does not cause the default behavior of an event to occur (such as a form submission).
    • While .trigger() will operate on all elements matched by the jQuery object, .triggerHandler() only affects the first matched element.
    • Events created with .triggerHandler() do not bubble up the DOM hierarchy; if they are not handled by the target element directly, they do nothing.
    • Instead of returning the jQuery object (to allow chaining), .triggerHandler() returns whatever value was returned by the last handler it caused to be executed. If no handlers are triggered, it returns undefined

提交回复
热议问题