tanakahdaのプログラマ手帳

プログラミングとかソフトウェア開発とかの備忘録

はじめてのjQueryプラグイン

指定された要素内に「Hello World!」を出力するプラグインを作成する。

jQueryにメソッドを定義するには、jQuery.fnオブジェクトをメソッド名で拡張する。
jQueryオブジェクトは複数の結果に対処できなければならないので、
each()関数の呼び出しでラップし、カスタムコードをすべての結果に適用する。


JSファイルは下記のとおり。(jquery.helloworld.jsとする)

jQuery.fn.helloworld = function() {
    return this.each(function(){
        jQuery(this).append('Hello World!');
    });
};


HTMLファイルは下記のとおり。

<html>
<body>
    
    <div></div>
    <div></div>
    <div></div>
    
    <script type="text/javascript" src="jquery.js"></script>
<!-- 作ったプラグインファイル -->
    <script type="text/javascript" src="jquery.helloworld.js"></script>
    <script type="text/javascript">
        jQuery('div').helloworld();
    </script>
    
</body>
</html>


結果は下記のとおり。

Hello World!
Hello World!
Hello World!