如何创建简单的jQuery插件?

use*_*856 2 javascript jquery plugins jquery-plugins extend

这个测试插件应该像这样工作:当点击一个元素时,它会向下移动.就那么简单.

jQuery.fn.moveDown = function(howMuch){
    $(this).css("border", "1px solid black");
    $(this).click(function(){

        $(this).css("position", "relative");
        $(this).animate({top: '+='+howMuch});
    }); 
}
Run Code Online (Sandbox Code Playgroud)

问题是,当单击一个元素时,它不仅会移动被点击的元素,还会移动插件所应用的所有其他元素.

这是什么解决方案?

Bar*_*din 5

对于插件创作尝试这种方式,更加可靠:

编辑: 这是工作jsFiddle的例子.


插入:

(function($){
    $.fn.extend({
        YourPluginName: function(options) {
                var defaults = {
                      howMuch:'600',
                      animation: '',//users can set/change these values
                      speed: 444,
                      etc: ''
                }
        };

       options = $.extend(defaults, options);

       return this.each(function() {
          var $this = $(this);              
          var button = $('a', $this);// this represents all the 'a' selectors;
                                            // inside user's plugin definition.

          button.click(function() {
            $this.animate({'top':options.howMuch});//calls options howMuch value
          });
       });
})(jQuery);
Run Code Online (Sandbox Code Playgroud)

用户文档:

$(function() {
   $('#plugin').YourPluginName({
     howMuch:'1000' //you can give chance users to set their options for plugins
   });
});

<div id="plugin">
  <a>1</a>
  <a>2</a>
  <a>3</a>
</div>
Run Code Online (Sandbox Code Playgroud)