如何使用jQuery封裝插件

jQuery官方給了一套對象級別開發插件的模板 。

如果使用的是 sublimeText 編輯器,推薦安裝插件 jQuery,在文件中輸入 plugin + Enter 會自動生成代碼片段。

安裝成功後在 js 文件中輸入 plugin ,會出現下圖所示內容:

選擇 plugin (method basic),出現以下內容:

(function($) {
// What does the pluginName plugin do?
$.fn.pluginName = function(options) {

  if (!this.length) { return this; }

  var opts = $.extend(true, {}, $.fn.pluginName.defaults, options);

  this.each(function() {
    var $this = $(this);

  });

  return this;
};

// default options
$.fn.pluginName.defaults = {
  defaultOne: true,
  defaultTwo: false,
  defaultThree: 'yay!'
};

})(jQuery);

給插件起個名字,添加到紅框內 ,在綠框內設置所需的參數,在藍框內編寫插件的主方法。

在 HTML 中調用該插件:

引入 jQuery 和插件 js 文件,選擇 DOM 元素,調用插件。

可以參考下面這個封裝插件的實例:
<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <title>jQplugin</title>
</head>

<body>
    <div class="box">
        <input type="button" class="btn1" value="btn1">
        <input type="button" class="btn2" value="btn2">
    </div>
</body>

<script src="https://cdn.bootcss.com/jquery/3.3.1/jquery.min.js"></script>
<script>
// 插件封裝
(function($) {
    // What does the pluginName plugin do?
    $.fn.pluginName = function(options) {

        if (!this.length) {
            return this;
        }

        var opts = $.extend(true, {}, $.fn.pluginName.defaults, options);

        this.each(function() {
            var $this = $(this);
            $(opts.btn1).click(function(event) {
                alert($(this).val());
            });
            $(opts.btn2).click(function(event) {
                alert($(this).val());
            });

        });

        return this;
    };

    // default options
    $.fn.pluginName.defaults = {
        btn1: null,
        btn2: null
    };

})(jQuery);

// 調用插件
$(function() {
    $(".box").pluginName({
        btn1: ".btn1",
        btn2: ".btn2"
    })
});
</script>

</html>

期待您的關注!

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章