首页 > 设计 > WEB开发 > 正文

Building Your First jQuery Plugin

2019-11-04 07:44:36
字体:
来源:转载
供稿:网友

Building Your First jQuery Plugin

Step 1

The first step is to extend the actual jQuery object with the function that we wish to add. In our case, we wish to add "truncation" functionality. So here's where to start: create ajquery.truncate.jsfile and save it with the following code:

1 $.fn.truncate = function(options) {     2    return this.each(function() { 3    });4 };

Now you may have heard that plugin developers should not user the$alias, as this can result in conflicts with other libraries. This is only partially true. The following snippet is the same as the one above, except that we passjQueryinto the function, allowing us to use an alias we want. We'll stick with$.

1 (function($){2  $.fn.truncate = function() {3 4     return this.each(function() {5 6     });7  };8 })(jQuery);
Step 2

Before we go any further, let's create a simple test page that we can use to test our plugin. Create a page and call itwhatever_you_want.html. Insert the following code. As you can see I placed both the jQuery library and the plugin inside a folder namedjs. Note that we are already invoking our plugin in this snippet, although we have not yet coded any behavior.

 1 <html> 2 <head> 3  <title>Truncation Plugin Test</title> 4  <script src="js/jquery.js" type="text/javascript"></script> 5  <script src="js/jquery.truncate.js" type="text/Javascript"></script> 6   7  <script type="text/javascript"> 8   $().ready(function() { 9    $('.tip').truncate();10   });11  </script>12 </head>13 <body>14  <div class="tip" style="width:200px;background-color:#ccc;padding:10px;">15   Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Etiam fringilla, purus a ultrices blandit,16   odio ante scelerisque neque, vitae imperdiet odio velit ac nisl. Sed tortor metus, placerat condimentum,17   feugiat in, feugiat adipiscing, mi. Donec pulvinar sem vitae leo. Vestibulum eget lectus et ligula hendrerit18   pharetra. Sed porta justo ac nisl. Aliquam nisi erat, pellentesque sed, sagittis eu, fringilla sit amet,19   dolor. Nam ac mi. Pellentesque pede purus, mattis aliquet, semper nec, cursus a, orci. Duis bibendum nibh20   ac massa. Integer eu tortor. Aenean convallis quam at nunc. Nunc mollis tincidunt nisi. Suspendisse mauris21   odio, iaculis ut, feugiat vitae, ultrices in, tortor. Quisque at elit. In hac habitasse platea dictumst.22  </div>23 </body>24 </html>
Step 3

The next thing we want to do is PRovide a mechanism for the user to customize the plugin. While we want to make the plugin as flexible as possible, we should also provide defaults so that the user isn't forced into providing a long list of parameters. We can easily do this using jQuery'sextendmethod. Update your plugin to match the following:

 1 (function($){ 2  $.fn.truncate = function(options) { 3  4   var defaults = { 5    length: 300, 6    minTrail: 20, 7    moreText: "more", 8    lessText: "less", 9    ellipsisText: "..."10   };11   var options = $.extend(defaults, options);12     13   return this.each(function() {14 15   });16  };17 })(jQuery);

For now we won't override any of the defaults in our test page, but we'll demonstrate this later.

Step 4

So that takes care of all the preliminary considerations. Let's get to coding the plugin's functionality. As you've already seen, the plugin is returningthis.each(...). This line will execute the contained anonymous function on each item in the jQuery array. So, if for example we called$('p').truncate(), the code we're about to write would execute on everyptag.

Since I'm assuming a comfortable understanding of jQuery, I won't explain in detail how the function's code actually works. If anything in the code is not obvious, you should refer to thedocumentationor ask a question in the comments. To complete your plugin, update it to match the following:

 1 (function($){ 2  $.fn.truncate = function(options) { 3      4   var defaults = { 5    length: 300, 6    minTrail: 20, 7    moreText: "more", 8    lessText: "less", 9    ellipsisText: "..."10   };11   12   var options = $.extend(defaults, options);13     14   return this.each(function() {15    obj = $(this);16    var body = obj.html();17    18    if(body.length > options.length + options.minTrail) {19     var splitLocation = body.indexOf(' ', options.length);20     if(splitLocation != -1) {21      // truncate tip22      var splitLocation = body.indexOf(' ', options.length);23      var str1 = body.substring(0, splitLocation);24      var str2 = body.substring(splitLocation, body.length - 1);25      obj.html(str1 + '<span class="truncate_ellipsis">' + options.ellipsisText + 26       '</span>' + '<span  class="truncate_more">' + str2 + '</span>');27      obj.find('.truncate_more').CSS("display", "none");28      29      // insert more link30      obj.append(31       '<div class="clearboth">' +32        '<a href="#" class="truncate_more_link">' +  options.moreText + '</a>' + 33       '</div>'34      );35 36      // set onclick event for more/less link37      var moreLink = $('.truncate_more_link', obj);38      var moreContent = $('.truncate_more', obj);39      var ellipsis = $('.truncate_ellipsis', obj);40      moreLink.click(function() {41       if(moreLink.text() == options.moreText) {42        moreContent.show('normal');43        moreLink.text(options.lessText);44        ellipsis.css("display", "none");45       } else {46        moreContent.hide('normal');47        moreLink.text(options.moreText);48        ellipsis.css("display", "inline");49       }50       return false;51        });52     }53    } // end if54    55   });56  };57 })(jQuery);

You'll notice that whenever I needed to select an element within the plugin, I always usedobjas my context (e.g.,moreLink = $('.truncate_more_link', obj)). This is necessary to constrain any selections to the current truncated element. Without setting the context like this, you will get unpredictable results.

So that's it - your first jQuery plugin! We're not quite finished though, since I promised we'd demonstrate overriding the default options. In the following example, every option has been over ridden, although it is perfectly valid to override fewer. Just replace the script in your test page with this:

1 $().ready(function() {2  $('.tip').truncate( {3   length: 120,4   minTrail: 10,5   moreText: 'show more',6   lessText: 'show less',7   ellipsisText: " [there's more...]"8  });9 });

http://blog.jeremymartin.name/2008/02/building-your-first-jquery-plugin-that.html


发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表