简体   繁体   中英

Does setTimeOut function in Jquery works with Jquery.fn.extend({ });

I have one div element

  <div id="progressbar1"></div>

then through jquery I am declaring one function

$(function() {
    $("#progressbar1").increment({target:200});
});

jQuery.fn.extend({
    increment:function(obj){
        console.log($(this).children().attr("value-now"));
        var current_val=$(this).children().attr("value-now");
        var max_val=obj.target||$(this).children().attr("value-max");
        if(current_val<max_val)
        {
            current_val++;
            var widthp=current_val/max_val;
            widthp=widthp*100;
            $(this).children().width(widthp.toFixed(0)+"%");
            setTimeout(increment,100);
        }
    }
});

But with SetTimeout function error is coming function increment is not defined.If I remove setTimeout increment is working fine.So I want to know whether Jquery.fn.extend works with setTimeout or not??

As setTimeout is just JavaScript, and jQuery is also just JavaScript, yes you can use it in a jQ method.

You are referencing something named increment as the function to run in your setTimeout line. You have not, however, defined any such function named increment .

increment is a method you've defined on the jQuery prototype, so replace your setTimeout line with this:

var $this = $(this);
setTimeout(function () {
    $this.increment(obj);
}, 100);

Here's a full version of your code with some cleanup (untested):

jQuery.fn.extend({
    increment: function (obj) {
        return this.each(function () {
            var $this = $(this),
                children = $this.children(),
                current_val = children.attr('value-now'),
                max_val = obj.target || children.attr('value-max'),
                widthp;

            if (current_val < max_val) {
                current_val++;
                // you'll probably want to update `children.attr('value-now')` here
                widthp = (current_val / max_val) * 100;
                children.width(widthp.toFixed(0) + '%');

                setTimeout(function () {
                    $this.increment(obj);
                }, 100);
            }
        });
    }
});

$(function() {
    $("#progressbar1").increment({target:200});
});

Right now increment is not defined anywhere. What you need is to call $.fn.increment method. One more approach to do it properly is using $.proxy :

setTimeout($.proxy(this.increment, this), 100);

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