开发者

Authoring a plugin function with jQuery

开发者 https://www.devze.com 2023-02-24 08:27 出处:网络
Hey dudes, I have the following function: $.fn.slideOut = function(speed,dir) { this.animate({ 开发者_StackOverflow中文版dir: \'-1000px\'

Hey dudes, I have the following function:

$.fn.slideOut = function(speed,dir) { 
        this.animate({
          开发者_StackOverflow中文版  dir: '-1000px'
        }, speed);
    };

But the direction (dir) isn't being carried over and isn't giving me an error either.

I'm calling it like so: $('#element').slideOut(500,'top');

So my quesiton = why is it not animating? :(


You can't use a variable on the left-hand (name) side of an object literal property initializer, what you have there is actually the property name "dir". You'll have to do it like this:

$.fn.slideOut = function(speed,dir) { 
    var opts = {};
    opts[dir] = '-1000px';
    this.animate(opts, speed);
};

A bit off-topic, but probably worth pointing out that that plug-in function won't chain. Unless you have a good reason not to, return this for chainability (in this case, you can just return what animate returns, since animate returns this):

$.fn.slideOut = function(speed,dir) { 
    var opts = {};
    opts[dir] = '-1000px';
    return this.animate(opts, speed);
};


If you want to use a variable property name, you cannot use object literals. You first have to create the object and then set the property with the "array access" syntax:

$.fn.slideOut = function(speed,dir) {
    var options = {};
    options[dir] = '-1000px';
    this.animate(options, speed);
};


you are calling

this.animate({
  dir: '-1000px'
}

in your plugin. It is normal that it doesn't use the one received as a parameter.

0

精彩评论

暂无评论...
验证码 换一张
取 消