本文實例講述了jquery插件格式。分享給大家供大家參考,具體如下:
現在打算給公司寫一個公共組件,常用的工具很多都是jquery,很多時候一些插件特效也是基於jquery寫的,因此工作中難免會遇到要拓展別人寫的插件。
下面我簡單的描述一下插件的格式:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<script src="jquery-1.6.2.min.js" type="text/javascript"></script>
<script type="text/javascript">
//模擬一個小的插件,方便大家學習
(function($){
$.fn.huangbiao=function(userSetting){
//利用jquery的extend方法來拓展插件的配置參數,這個應該暴露給使用用戶
settings = jQuery.extend($.fn.huangbiao.defaultSetting,userSetting);
function init(){
alert("在我這裡進行初始化");
myFunction(this);
}
function myFunction(obj){
alert("我是開發者自己封裝的函數");
showSetting();
privateFunc();
}
function showSetting(){
alert(this.settings.name);
}
this.unbind('click').click(init);
return this;
}
//下面這個是閉包的私有函數
function privateFunc(){
alert("i am private function!");
}
//暴露給用戶使用的函數
$.fn.huangbiao.openFunc=function(obj){
alert("test");
}
/*
定義暴露給用戶的默認值
這個一定要放在$.fn.huangbiao對象後面,否則腳本會報錯的
*/
$.fn.huangbiao.defaultSetting={
name:"huangbiao",
sex:"boy",
age:24
};
})($);
function useUndefault(){
//使用自己配置的參數
$("#undefault").huangbiao({name:"liumei",sex:"girl",age:24});
}
function useUndefault2(){
alert($.fn.huangbiao.defaultSetting.name);
$.fn.huangbiao.defaultSetting.name="hanmeimei";
alert($.fn.huangbiao.defaultSetting.name);
//使用自己配置的參數
$("#undefault2").huangbiao();
}
function useDefault(){
//使用默認的配置參數
$("#default").huangbiao();
}
function openFunction(){
$("#default").huangbiao.openFunc();
}
</script>
<title>無標題文檔</title>
</head>
<body>
<input type="button" value="useUndefault" id="undefault" onclick="useUndefault();"><br>
<input type="button" value="useUndefault2" id="undefault2" onclick="useUndefault2();"><br>
<input type="button" value="useDefault" id="default" onclick="useDefault();"><br>
<input type="button" value="使用提供給用戶的函數" id="openFuncId" onclick="openFunction();"><br>
</body>
</html>
另外,這裡再提供一個關於jquery的文檔,相信對於大家學習jQuery插件有一定幫助作用!
本站下載: jQuery插件開發.pdf 。