2011-05-17 61 views
0

我使用這個代碼:打開這段代碼爲jQuery插件

$('div.x').find('#y').live('click', function(e) { 

     var aa = $(this); 

    if (aa.find('a').length == 0) { 

     aa.find('div.z').hide(); 

     aa.find('input:submit').click(function(e) { 
      //................... 
     }); 

     aa.append('xxx'); 
     $('html, body').animate({ scrollTop: 100 }); 
    } 
    e.preventDefault(); 

}); 


$('body').click(function(e) { 
    $('div.tt').slideUp('slow'); 
}); 

$('div.uu').delegate('div.gg', 'click', function(e) { 
    e.stopPropagation(); 
}); 

現在我想上面這段代碼到jQuery插件。你能告訴我我該怎麼做?如何接受來自外部的默認設置,以便div類可以從外部獲取,而不是將該硬編碼保存在插件中?

+0

我發佈了一個答案,但是如果你告訴我什麼類型的東西會是選項,那麼我可以給你看一個例子,但是請看:http://docs.jquery.c om/Plugins/Authoring – 2011-05-17 20:59:57

+0

http://docs.jquery.com/Plugins/Authoring – machineghost 2011-05-17 20:44:44

回答

1

你可以使用這個,你只需要改變一些東西:
https://github.com/OscarGodson/jQuery-Plugin-Skeleton

這是未經測試,但我相信它應該工作:

/* 
    Copyright (c) <Year> <First & Last Name>, <Your Web Site> 

    Permission is hereby granted, free of charge, to any person obtaining 
    a copy of this software and associated documentation files (the 
    "Software"), to deal in the Software without restriction, including 
    without limitation the rights to use, copy, modify, merge, publish, 
    distribute, sublicense, and/or sell copies of the Software, and to 
    permit persons to whom the Software is furnished to do so, subject to 
    the following conditions: 

    The above copyright notice and this permission notice shall be 
    included in all copies or substantial portions of the Software. 

    THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, 
    EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF 
    MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND 
    NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE 
    LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION 
    OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION 
    WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. 
*/ 
(function($){ 
    $.fn.pluginname = function(options) { 
     var settings = $.extend({}, $.fn.pluginname.defaultOptions, options); 

     return this.each(function() { 
      var $this = $(this); 


     $this.find('#y').live('click', function(e) { 

      var aa = $(this); 

      if (aa.find('a').length == 0) { 

       aa.find('div.z').hide(); 

       aa.find('input:submit').click(function(e) { 
        //................... 
       }); 

       aa.append('xxx'); 
       $('html, body').animate({ scrollTop: 100 }); 
      } 
      e.preventDefault(); 

     }); 


     $('body').click(function(e) { 
      $('div.tt').slideUp('slow'); 
     }); 

     $('div.uu').delegate('div.gg', 'click', function(e) { 
      e.stopPropagation(); 
     }); 

     }); 
    }; 

    $.fn.pluginname.defaultOptions = { 
    }; 
})(jQuery); 

你幾乎像這樣使用:

$('div.x').pluginname();