Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
135 views
in Technique[技术] by (71.8m points)

javascript - How to create simple jQuery plugin?

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.

What is the solution for this?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

For plugin authoring try this way, much more solid:

Edit: Here is working jsFiddle example.


PLUGIN:

(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);

USER'S DOCUMENT:

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...