zoukankan      html  css  js  c++  java
  • 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.js file 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 pass jQuery into 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 it whatever_you_want.html. Insert the following code. As you can see I placed both the jQuery library and the plugin inside a folder named js. 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="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 hendrerit
    18   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 nibh
    20   ac massa. Integer eu tortor. Aenean convallis quam at nunc. Nunc mollis tincidunt nisi. Suspendisse mauris
    21   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'sextend method. 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 returning this.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 every p tag.

    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 thedocumentation or 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 tip
    22      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 link
    30      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 link
    37      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 if
    54    
    55   });
    56  };
    57 })(jQuery);

    You'll notice that whenever I needed to select an element within the plugin, I always used obj as 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

  • 相关阅读:
    arcgis for silverlight 控制图层显示级别
    Telerik for silverlight RadAutoCompleteBox 动态数据源
    ARM嵌入式学习--OK6410裸板程序--2.GPIO控制LED跑马灯(从ARM汇编跳转到C语言)
    ARM嵌入式学习--OK6410裸板程序--1.GPIO控制LED
    Linux内核移植--1.添加NAND Flash分区
    Linux 快速释放端口与释放内存缓存
    jquery ajax session超时处理
    相濡以沫不如相忘江湖
    SQL Server数据库无法启动(万金油解决办法)
    多显示器实现屏幕扩展(VGA DVI HDMI)
  • 原文地址:https://www.cnblogs.com/aucrux/p/4369075.html
Copyright © 2011-2022 走看看