jQuery插件开发

jQuery插件开发方式主要有三种:

1.通过$.extend()来扩展jQuery
2.通过$.fn 向jQuery添加新的方法
3.通过$.widget()应用jQuery UI的部件工厂方式创建

通常我们使用第二种方法来进行简单插件开发

a.先说说$.extend()

<!doctype html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>jQuery插件</title>
    <script type="text/javascript" src="./2.1.js"></script>
    <script type="text/javascript" src="./demo.js"></script>
</head>
<body>
     <script type="text/javascript">
      
      $.sayHello();
      $.sayHello('wuheng111');
      // $.sayBye();
     </script>
</body>
</html>

a-1,demo.js  (核心部分)

 // alert("aaaa");
 $.extend({
       sayHello:function(name){
           console.log('Hellow ,'+ name);
           // alert(name);
       }
       
      });

注意:插件的语法,以及如何调用的。

b.现在说说:$.fn


<!doctype html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>jQuery插件学习</title>
    <script type="text/javascript" src="./2.1.js"></script>
    <script type="text/javascript" src="./myplugin.js"></script>

</head>
<body>
       <a href="http://www.baidu.com/">1111</a>
      <a href="2222">22222</a>
      <a href="333">33333</a>
      <a href="444">44444</a>
      <hr/>
      <p>aaaa</p>
      <p>bbbbb</p>
      <p>ccccc</p>
      <p>ddddd</p>
     
    <script type="text/javascript">
      $("a:first").myPlugin();
      // $("p:last").myPlugin();
    </script>
</body>
</html>


b-1,myplugin.js(核心部分)

$.fn.myPlugin = function(){
  //在这里面,this指的是用jQuery选中的元素
//example :$('a'),则this=$('a')
this.css('color', 'red');
this.each(function() {
//对每个元素进行操作
$(this).append(' ' + $(this).attr('href'));
});
}

注意:插件的语法,以及如何调用的。

来源:http://www.shouce.ren/post/view/id/52914

原文地址:https://www.cnblogs.com/wuheng1991/p/5305703.html