如何创建简单的 jQuery 插件?

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

This test plugin, is supposed to work like this: When an element is clicked, it moves down. Simple as that.

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

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

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

The problem is, when an element is clicked, it not only moves the clicked element but also ALL the other elements which the plugin was applied to.

解决办法是什么?

推荐答案

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

For plugin authoring try this way, much more solid:

这是 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);

用户文件:

$(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>

相关文章