简体   繁体   中英

Loop Function in JQuery Plugin

I'm trying to make a recursive function in a jquery plugin that was made to change the image src attribute (and thus change the image...) again and again with set intervals in between. Now, when I log the data onto my console, the value of x is increasing as needed, but my images aren't changing.

So what I did was I logged $(this).attr("id") to cross check. Now the first time my function ran, my element's id was logging correctly but the second time, it was coming undefined . So something's wrong.

I need help in solving this problem and basically make the image change repeatedly.

Here is my plugin code:

(function($) {

$.fn.addimate = function(noOfImages, prefix, x, extension, interval) {

    if (x > noOfImages) {
        x = 1;
    }

    console.log($(this).attr("id") + "\n" + prefix + x + extension + "\n" + interval);
    $(this).attr("src", prefix + x + extension);
    x ++;

    setTimeout(function() {
        $(this).addimate(noOfImages, prefix, x, extension, interval);
    }, interval);
}

}) (jQuery);

Help is HIGHLY appreciated. Thanks...

When writing a jQuery plugin, you should understand that you're working with the jQuery object in the anonymous function because you're passing in jQuery to the function. So, when working with the jQuery instance, you don't need to use $(this) to work with the object. What you're doing when you use $(this) when in the jQuery namespace, is you're attempting to create a jQuery object of the jQuery object. That being said, this is not desirable, nor valid.

Take your code, for example:

(function($) {

$.fn.addimate = function(noOfImages, prefix, x, extension, interval) {

    //Intentionally deleted content.
}; //AND you're missing a semicolon here

}) (jQuery);

When someone calls $('.selector').addimate(), they're passing in $(.selector) to you're function. So, you're already working with a jQuery object. You're code should look like this.

(function($) {

$.fn.addimate = function(noOfImages, prefix, x, extension, interval) {

    var $this = this; //This will maintain the context of the jQuery object.

    if (x > noOfImages) {
        x = 1;
    }

    console.log(this.attr("id") + "\n" + prefix + x + extension + "\n" + interval);
    this.attr("src", prefix + x + extension);
    x++;

    setTimeout(function() {
        $this.addimate(noOfImages, prefix, x, extension, interval);
    }, interval);
};

}(jQuery));

Please see this fiddle: http://jsfiddle.net/m2X4E/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM