随着jQuery的更新,其实很多好用但又不为人知的函数默默的躺在那里,我准备花些时间整理一下。–北北
1.jQuery.Event
自定义一个事件,第一个参数是你的事件名称,第二个是你的自定义方法。
var e = jQuery.Event( “divchanged” , function(){ … });
用trigger函数调用这个事件 $( “body” ).trigger( e );
2.jQuery.proxy(function,context)
var you = { type: “person”, test: function(event) { $(“#log”).append( this.type + ” ” ); } $(“#test”).click(you.test);
调用这句相当于调用:
$(“#test”).click(function(event){ $(“#log”).append( this.type + ” ” ); });
所以这里的this指的是$(“#test”).
如果这样调用:
$(“#test”).click($.proxy(you.test,you));
此时的调用相当于:
$(“#test”).click(function(event){ $(“#log”).append( you.type + ” ” ); });
虽然调用事件的对象是$(“#test”),但是却可以使用$.proxy把事件执行内的对象改变为you。
3.jQuery.proxy(context,functionname):
第一个参数是你想proxy的对象,第二个参数为要改变的函数的名字。
var obj = { name: “John”, test: function() {
$(“#log”).append( this.name );
$(“#test”).unbind(“click”, obj.test);
}
};
$(“#test”).click( jQuery.proxy( obj, “test” ) );
把obj作为context传入test中,而不是$(“#test”). 这个执行完之后,结果会是John,
如果使用下面这句 $(“#test”).click(obj.test);
结果会是$(“#test”).的name值。
4.jQuery.each(function(){})的打断机制
在jQuery里,要打断each循环不能直接使用continue或break 要实现break和continue的功能可以用retrun代替
break — 用return
false;
continue — 用return ture;