jQuery:从触发器返回值 [英] Jquery: Returning Value From Trigger
问题描述
我正在使用触发器调用从自定义事件中获取值,但是我希望它返回一个值,并且在执行以下调用时它仅给我Object对象:
I am using a trigger call a get a value from custom event but I want it to return a value and its only giving me Object Object when I do the following call:
var user_id=$("#my_div").trigger("get_id", [username]);
我的触发事件函数如下:
My trigger event function looks like this:
$("#my_div").on("get_id", function(e, username){
var user_id;
if (username='fred'){
user_id=1;
}
else if(username='mario'){
user_id=2;
}
return user_id;
});
推荐答案
您不能从触发器返回值,但是可以用许多不同的方式存储信息,一种方式是将对象用作参数:
You cannot return a value from a trigger, but you can store information in many different ways, one way is using a object as a parameter:
//event
$("element").on("click", function(event, informationObj) {
informationObj.userId = 2; //you have to access a propery so you can modify the original object
});
//trigger
var informationObj = {userId : 0};
$("element").trigger("click", [informationObj ]); //informationObj.userId === 2
另一种方法是使用jQuerys .data()
方法
other way is using jQuerys .data()
method
//event
$("element").on("click", function() {
$(this).data("userId", 2);
});
//trigger
$("element").trigger("click").data("userId") //2
您可以做的另一件事是修改在事件外部声明的变量,然后在调用触发器后使用它,或将其作为属性存储在具有
Another thing you can do is modifying a variable that's declared outside the event and then using it after calling the trigger, or storing it as a property in the element that has the event with the this
keyword like this:
//inside the event function
this.userId = 2;
//outside the event
$("element").trigger("click").get(0).userId
希望有帮助.
此外,请使用.triggerHandler()
在下面查看 @ Arm0geddon答案,只是要注意它具有某些方面效果,例如不冒泡DOM层次结构.
Also, take a look at @Arm0geddon answer below, using .triggerHandler()
, just beware that it has some side effects, like not bubbling up the DOM hierarchy.
这篇关于jQuery:从触发器返回值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!