<script type="text/javascript"> (function($,sr){ var debounce = function (func, threshold, execAsap) { var timeout; return function debounced () { var obj = this, args = arguments; function delayed () { if (!execAsap) func.apply(obj, args); timeout = null; }; if (timeout) clearTimeout(timeout); else if (execAsap) func.apply(obj, args); timeout = setTimeout(delayed, threshold || 100); }; } jQuery.fn[sr] = function(fn){ return fn ? this.bind('resize', debounce(fn)) : this.trigger(sr); }; })(jQuery,'smartresize');
</script>
特别是这句,jQuery.fn[sr] = function(fn){ return fn ? this.bind('resize', debounce(fn)) : this.trigger(sr); };jQuery.fn[sr] 是什么意思,谢谢!!javascriptjquery
var debounce = function (func, threshold, execAsap) {
var timeout;
return function debounced () {//闭包
var obj = this, args = arguments;
function delayed () {
if (!execAsap)//定时执行
func.apply(obj, args);
timeout = null;
};
if (timeout) //有定时器时清理
clearTimeout(timeout);
else if (execAsap)//立刻执行
func.apply(obj, args);
timeout = setTimeout(delayed, threshold || 100);//定时器
};
}
//jQuery.fn[sr] 加入jQuery对象,成为对象的一个方法
//用法是 jQuery(xx).smartresize(fn);
//有fn时注册resize事件,resize后threshold或100毫米后执行fn
//没有fn则立刻执行已经注册的fn
jQuery.fn[sr] = function(fn){ return fn ? this.bind('resize', debounce(fn))
: this.trigger(sr); };
})(jQuery,'smartresize');
通过var aa="sfdfdsfd" aa.trim(),就可以调用你写的trim方法了。
jQuery.fn[sr] = function(fn){ return fn ? this.bind('resize', debounce(fn)) 是在jquery的原型对象上添加一个名为sr(也就是传入的参数“smartresize”)的方法,传入参数是一个function,return之后是判断如果function存在,则讲function绑定到resize事件上