Update global variable from jquery nested function

旧时模样 提交于 2019-12-25 04:06:23

问题


I have a problem with this piece of code:

var elements;
var current = 100;

$(document).ready(function() {
        elements =  = $('.slide').length;
        iterate();
});

function iterate() {
        $('.slide').eq(current).hide().queue(
                function() {
                        if (++current >= elements) { current = 0; }
                        $('.slide').eq(current).show();
                        $(this).dequeue();
                }
        );

        // Call this function again after the specified duration
        setTimeout(iterate, 1000);
}

What I'm trying to do is iterate all elements with 'slide' class but I have a problem updating 'current' variable. Its value is always 0. How can I modify a global variable from inside a nested jquery function?


回答1:


If this line is invoked before the DOM is ready, .length is 0:

var elements = $('.slide').length;

Which means the condition for this if will always be true:

if (++current >= elements) { current = 0; }

You can fix it like this:

var elements;
var current = 100;

$(document).ready(function() {
    elements = $('.slide').length;
    iterate();
});

Also, this is a little bit of an odd use of .queue(). There's nothing that needs queueing.

I'd rework it like this:

function iterate() {
    var slide = $('.slide').eq(current).hide();
    if (++current >= elements) { current = 0; }
    $('.slide').eq(current).show();

    // Call this function again after the specified duration
    setTimeout(iterate, 1000);
}


来源:https://stackoverflow.com/questions/12944141/update-global-variable-from-jquery-nested-function

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!