从jQuery嵌套函数更新全局变量 [英] Update global variable from jquery nested function

查看:203
本文介绍了从jQuery嵌套函数更新全局变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对这段代码有疑问:

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

我想做的是用'slide'类迭代所有元素,但是更新'current'变量时遇到问题.它的值始终为0.如何从嵌套的jquery函数内部修改全局变量?

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?

推荐答案

如果在DOM准备就绪之前调用此行,则.length0:

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

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

这意味着该if的条件将始终为true:

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

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

您可以这样解决它:

var elements;
var current = 100;

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

此外,这是.queue()的奇怪用法.没有什么需要排队的.

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

我会这样修改它:

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

这篇关于从jQuery嵌套函数更新全局变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆