$.fnでjQueryプラグインを作成するサンプル

2022年2月21日

環境
jquery 3.6.0

書式
1.プラグインの定義
$.fn.プラグイン名 = function(引数){
処理コード
};
プラグインはメソッドチェーンに対応させるため、自身thisを返します。
2.プラグインを呼び出す
$(“セレクタ名").プラグイン名(引数)

使用例

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<script>
$(function(){
(function($){
//文字サイズをセットする
$.fn.setFontSize = function(size){
this.css("font-size", size);
return this;
};
//文字色をセットする
$.fn.setFontColor = function(str){
this.css("color", str);
return this;
};
}(jQuery));
//ボタンを押下後イベント
$('#btnShow').click(function(){
//文字色にred、文字サイズに28を設定
$("#cft").setFontColor("red").setFontSize(28);
});
});
</script>
</head>
<body>
<div id="cft">東京tokyo</div>
<input type="button" value="検証" id="btnShow">
</body>
</html>
<!DOCTYPE html> <html> <head> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script> <script> $(function(){ (function($){ //文字サイズをセットする $.fn.setFontSize = function(size){ this.css("font-size", size); return this; }; //文字色をセットする $.fn.setFontColor = function(str){ this.css("color", str); return this; }; }(jQuery)); //ボタンを押下後イベント $('#btnShow').click(function(){ //文字色にred、文字サイズに28を設定 $("#cft").setFontColor("red").setFontSize(28); }); }); </script> </head> <body> <div id="cft">東京tokyo</div> <input type="button" value="検証" id="btnShow"> </body> </html>
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<script>
$(function(){
  (function($){
  
    //文字サイズをセットする
    $.fn.setFontSize = function(size){
      this.css("font-size", size);
      return this;  
    };
    
   //文字色をセットする
    $.fn.setFontColor = function(str){
      this.css("color", str);
      return this;  
    };
  }(jQuery));
 
  //ボタンを押下後イベント
  $('#btnShow').click(function(){
   //文字色にred、文字サイズに28を設定
    $("#cft").setFontColor("red").setFontSize(28);  
  });
});
</script>
</head>
<body>
  <div id="cft">東京tokyo</div>
  <input type="button" value="検証" id="btnShow">
</body>
</html>

結果
「検証」ボタンを押すと、「東京tokyo」の文字が赤色、文字のサイズは28になります。

jQuery

Posted by arkgame