本文介绍了使用jQuery .trigger调用返回值的自定义函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
有没有办法使用jQuery的.bind()和.trigger()调用来执行用户定义的函数(例如:save())并根据该方法的返回采取行动?例如:
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:
$("#aForm").bind ('save', function () {
return true;
});
然后:
if ($("#aForm").trigger ('save') == true) {
doSomething ();
}
推荐答案
我知道这个问题很古老,但这也许可以帮助某个人.
I know this question is old, but maybe this can help someone.
正如Paliath所指出的,您不能返回值,因为触发事件是异步的.您可以做的是将一个对象作为参数传递给事件.默认情况下,javascript对象始终是原始对象的引用.
As Paliath pointed, you can't return a value because the trigger event is asynchronous.What you can do, is pass a object as parameter to the event. By default, javascript objects are always references to the original.
例如:
绑定:
$(...).bind('example',function (evt,ret) {
ret.val = false;
});
触发:
var ret = {ret:true};
$(...).trigger('example',[ret]);
if (!ret.ret)
//event return false
else
//event returned true
这篇关于使用jQuery .trigger调用返回值的自定义函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!