jQuery外掛製作簡單介紹

admin發表於2017-03-01
將程式碼以外掛形式呈現將會是一種非常好的選擇,因為這樣程式碼的可重用性將會大大加強,下面就來簡單介紹一下如何製作jQuery外掛,希望能夠給需要的朋友帶來一定的幫助。

一.jQuery物件(類)的靜態函式:

程式碼例項如下:

[JavaScript] 純文字檢視 複製程式碼
jQuery.foo = function() { 
alert("螞蟻部落歡迎您"); 
};

完整程式碼:

[HTML] 純文字檢視 複製程式碼
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="author" content="http://www.softwhy.com/" />
<title>自定義外掛-螞蟻部落</title>
<script type="text/javascript" src="mytest/jQuery/jquery-1.8.3.js"></script> 
<script type="text/javascript">   
jQuery.foo=function(){  
  alert("螞蟻部落歡迎您");  
};
jQuery.foo();
</script>
</head>
<body>
</body>   
</html>

如果靜態函式較多的話可能會使名稱容易混淆,那麼採用名稱空間模式將是一個良好的選擇。

程式碼如下:

[JavaScript] 純文字檢視 複製程式碼
jQuery.foos={  
  fun1:function(){  
    console.log("螞蟻部落一");  
  },  
  fun2:function(){  
    console.log('螞蟻部落二');  
  }  
}

二.物件例項方法:

程式碼如下:

[JavaScript] 純文字檢視 複製程式碼
(function($){     
  $.fn.setbgColor=function(){
    $("#thediv").css("backgroundColor","blue");
  };
})(jQuery);

完整程式碼如下:

[HTML] 純文字檢視 複製程式碼
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="author" content="http://www.softwhy.com/" />
<title>自定義外掛-螞蟻部落</title>
<style type="text/css">
#thediv
{
  width:100px;
  height:100px;
  background-color:red;
}
</style>
<script type="text/javascript" src="mytest/jQuery/jquery-1.8.3.js"></script> 
<script type="text/javascript">   
(function($){     
  $.fn.setbgColor=function(){
    $("#thediv").css("backgroundColor","blue");
  };
})(jQuery);   
$(document).ready(function(){
  $('#thediv').setbgColor();  
})
</script>
</head>
<body>   
<div id="thediv"></div>
</body>   
</html>

相關文章