你的位置:首页 > 软件开发 > Java > 制作一个简洁的jquery插件

制作一个简洁的jquery插件

发布时间:2016-01-25 20:00:13
原文:http://mp.weixin.qq.com/s?__biz=MzAxMzgwNDU3Mg==&mid=401571467&idx=1&sn=08cb00963e6efd3881d3397903e84752&scene=1&srci ...

制作一个简洁的jquery插件

原文:http://mp.weixin.qq.com/s?__biz=MzAxMzgwNDU3Mg==&mid=401571467&idx=1&sn=08cb00963e6efd3881d3397903e84752&scene=1&srcid=0125cT8n9FJMI1u2faaQgjcS&from=singlemessage&isappinstalled=0#wechat_redirect

制作一个简洁的jquery插件但是这一次,代码是这样的:

制作一个简洁的jquery插件

它看起来简洁多了,而且也容易复用到别的项目当中。

2.插件结构

关于制作jquery插件,jquery官网提供了一份非常详细的说明文档。但是,我觉得它实在是太难理解了。

为了是我们的编程生活更美好一些,简单一些,我在线研究了相关的文档。下买呢的这段代码是一段优雅的jquery插件结构。

    1. //You need an anonymous function to wrap around your function to avoid conflict

    2. 匿名包裹函数,避免了全局变量

    3. (function($){

    4.  

    5.     //Attach this new method to jQuery

    6.     $.fn.extend({

    7.         

    8.         //This is where you write your plugin's name

    9.                // jquery插件名称

    10.         pluginname: function() {

    11.  

    12.             //Iterate over the current set of matched elements

      // 迭代选择器选中的dom元素

    1.         return this.each(function() {

    2.             

    3.                 //code to be inserted here

// jquery插件的代码

  1.             

  2.         });

  3.     }

  4.     });

  5.     

  6. //pass jQuery to the function,

  7. //So that we will able to use any valid Javascript variable name

  8. //to replace "$" SIGN. But, we'll stick to $ (I like dollar sign: ) )        

  9. })(jQuery);

3. Plugin With Options

如果你看过了第一部分的简介,padding值是可配置的。让用户根据自己的业务需求传递一些参数给插件是很有必要的。保证每一个变量都有一个默认值是一个良好的编程实践。现在,你需要下面的这段代码:

  1. (function($){

  2.  

  3.     $.fn.extend({

  4.         

  5.         //pass the options variable to the function

  6.         pluginname: function(options) {

  7.  

  8.  

  9.             //Set the default values, use comma to separate the settings, example:

  10.             var defaults = {

  11.                 padding: 20,

  12.                 mouseOverColor : '#000000',

  13.                 mouseOutColor : '#ffffff'

  14.             }

  15.                 

  16.             var options =  $.extend(defaults, options);

  17.  

  18.         return this.each(function() {

  19.                 var o = options;

  20.                 

  21.                 //code to be inserted here

  22.                 //you can access the value like this

  23.                 alert(o.padding);

  24.             

  25.         });

  26.     }

  27.     });

  28.     

  29. })(jQuery);

     

4. The animateMenu Plugin

现在您已经知道了jquery插件的基本结构。接下来的这个插件就是基于我之前的一个教程。它接收4个参数:

 

海外公司注册、海外银行开户、跨境平台代入驻、VAT、EPR等知识和在线办理:https://www.xlkjsw.com

原标题:制作一个简洁的jquery插件

关键词:jquery

*特别声明:以上内容来自于网络收集,著作权属原作者所有,如有侵权,请联系我们: admin#shaoqun.com (#换成@)。

可能感兴趣文章

我的浏览记录