jQuery爲開發插件提拱了兩個方法,分別是:html
jQuery.extend(object)ide
jQuery.fn.extend(object)函數
jQuery.extend(object); 爲擴展jQuery類自己.爲類添加新的方法。能夠理解爲添加靜態方法this
示例以下,返回兩個數種較大的一個spa
$.extend({prototype
Max:function(a,b){插件
if(a>b){htm
return a;對象
}else{開發
return b;
}
}
});
調用方法:
var max=$.Max(10,100);//返回兩個數種較大的一個
jQuery.fn.extend(object);給jQuery對象添加方法,對jQuery.prototype進行擴展,就是爲jQuery類添加「成員函數」。jQuery類的實例可使用這個「成員函數」。
查看fn的jQuery代碼以下:
jQuery.fn=jQuery.prototype={
init:function(select,context){}
};
發現jQuery.fn = jQuery.prototype,是對其提供擴展方法,
下面使用jQuery.fn開發一個小插件,但文本框獲取焦點之後清空文本框的內容
jQuery.fn.extend({
cleartext:function(){
$(this).focus(function(){
$(this).val("");
});
}
});
調用方法以下:
$(document).ready(function(){
$("input[type='text']").cleartext();
});
<html>
<head>
<title></title>
</head>
<body>
<input type="text" value="input username" />
</body>
</html>