jQuery事件函数传递参数

来源:互联网 发布:金山毒霸数据恢复 编辑:程序博客网 时间:2024/05/22 14:36

For thoroughness, I came across another solution which was part of the functionality introduced in version 1.4.3 of the jQueryclick event handler.

It allows you to pass a data map to the event object that automatically gets fed back to the event handler function by jQuery as the first parameter. The data map would be handed to the.click() function as the first parameter, followed by the event handler function.

Here's some code to illustrate what I mean:

// say your selector and click handler looks something like this...$("some selector").click({param1: "Hello", param2: "World"}, cool_function);// in your function, just grab the event object and go crazy...function cool_function(event){    alert(event.data.param1);    alert(event.data.param2);}

I know it's late in the game for this question, but the previous answers led me to this solution, so I hope it helps someone sometime!



jQuery事件参数传递模型:
注:trigger 不能与 bind 的原生函数一样,使用同样的参数传递形式;
参数传递一:
$(document).ready(function(){
 $("#btn").bind("click", function(event,a ,b){
   start(event, a, b);
  });
 $("#btn").trigger("click",["5", "6"]); //5,6可以不是字符串类型而为任意类型的数据;(回调函数)
 
});
function start(event, a, b){
 alert(a);
 alert(b);
}
参数传递二:
// 用户点击时,a和b是undefined类型
$(document).ready(function(){
 $("#btn").bind("click",{x:4,y:4}, function(event,a ,b){
   start(event, a, b);
  });
});
function start(event, a, b){
 alert(event.data.x);
 alert(event.data.y);
}

 

如何使用一的方法(代码触发click事件),加上二的参数传递方式来触发这个事件:
自己构建Event 对象;
 var e = jQuery.Event("click");
 e.a = 10;
 $("#btn").trigger(e);

注:

在使用bind方法时,其传递的参数必须是已经计算好的,如果是变量,那么它当前拥有的值则作为参数的永久值传递
( Both are  mechanisms for passing information to an event handler, but the extraParameters argument to .trigger() allows

information to be  determined at the time the event is triggered, while the eventData argument to .bind() requires the information

to be already  computed at the time the handler is bound);

 

根据以上测试结论:
1、Event.data."xx"-----------永远被绑定事件时的参数所覆盖(严格来说不是覆盖,而是对这个命名空间全部占有,而且是绑定时候就已近确定了data值);
2、使用代码触发Event,则自己定义一个命名空间: e.data2 = {a:56,....,.....,}; 然后再访问就不会造成值覆盖的问题;
3、1和2 的这两种策略又导致了另外一个问题:
在代码中如何才能统一的访问到这个数据,而不至于会导致数据的混乱,只想到一个愚蠢的办法,就是if/else 进行判断,整个流程如下:
注:(
判断一个值是否定义;
if(typeof obj == "undefined")
if(obj === undefined)

$(document).ready(function(){
 $("#btn").bind("click",{a:4,b:4}, function(event){
   start(event);
  });
 $("#hp").bind("click", help);
 });
function start(event){
 var a, b;
 if(event.data2 === undefined){
   a = event.data.a;
   b = event.data.b;
 }else{
   a = event.data2.a;
   b = event.data2.b; 
 }
 alert(a);
 alert(b);
}

function help(){
 var e = jQuery.Event("click");
 e.data2 = {
  a:5,
  b:5
  };
 $("#btn").trigger(e);
}


原创粉丝点击