jQuery插件开发详解

我们该如何扩展jQuery呢?主要可以通过下面2个来扩展:$.extend 和 $.fn

$.extend
如果把jQuery当成一个类,$.extend相当于为该类添加了静态方法extend。

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>demo</title>
</head>
<body>
  <script src="jquery.js"></script>
  <script>
      $.extend({
          log: function(message) {
              var now = new Date(),
                  y = now.getFullYear(),
                  m = now.getMonth() + 1,
                  d = now.getDate(),
                  h = now.getHours(),
                  min = now.getMinutes(),
                  s = now.getSeconds(),
                  time = y + '/' + m + '/' + d + ' ' + h + ':' + min + ':' + s;
                  console.log(time + ' My App: ' + message);
          }
      });
      $.log("出错啦!");
  </script>
</body>
</html>

  $.fn等于$.prototype

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>demo</title>
</head>
<body>
  <p class="text1">测试文字</p>
  <p class="text2">测试文字</p>
  <script src="jquery.js"></script>
  <script>
      $.fn.changeColor = function(options){
          this.defaults = {
              'color': '#000',
              'fontSize': '14px',
              'fontWeight': 'normal'
          };
          this.opt = $.extend(this.defaults, options);
          console.log(this.defaults);
          this.css({
              'color': this.opt.color,
              'font-size': this.opt.fontSize,
              'font-weight': this.opt.fontWeight
          });
      }
      $(".text1").changeColor();
      $(".text2").changeColor({'color': '#f06','fontSize': '18px','fontWeight': 'bold'});
  </script>
</body>
</html>

  

将我们要实现的代码封装在

;(function($,window,document,undefined){
    //想要实现的功能的代码
})(jQuery,window,document);
这里的";"最好添加上,可以避免代码压缩时出现问题
posted @ 2016-12-09 10:54  流星划过1210  阅读(251)  评论(0编辑  收藏  举报