JavaScript全局变量未更新

时间:2012-03-11 13:50:27

标签: javascript jquery

我正在写一些jQuery的逻辑问题。我怀疑我的全局变量做错了,但我不确定问题是什么。我正在记录正在运行的所有内容,出于某种原因,在我的rollDown()函数中,虽然我使用id++,但我的全局id变量未更新(如图所示)日志)。

我需要更新我的全局变量,以便当我点击header > a时,else if语句将会运行而不是再次触发rollDown()

以下是相关代码:

var id = 0;
var animSpeed = 0;
var animDelay = 0;
var working = 0;
var items = 0;

function logs() {
    "use strict";
    console.log('id: ' + id);
    console.log('-----');
    console.log('animSpeed: ' + animSpeed);
    console.log('-----');
    console.log('animDelay: ' + animDelay);
    console.log('-----');
    console.log('working: ' + working);
    console.log('==============');
}

function rollDown(items, id) {
    "use strict";
    var dist = $('li').eq(id).outerHeight(), slideDown = {'margin-top' : '+=' + dist + 'px'};
    console.log('items: ' + items + ' & id: ' + id);
    if (id <= items) {
        if (id === 0) {
            $('#toggle').html('Hide &uarr;');
        }
        $('li').not($('li').eq(id).prevAll()).delay(animDelay).animate(slideDown, animSpeed);
        id++;
        logs();
        rollDown(items, id);
    } else {
        console.log('herp derp');
        logs();
    }
}

function getVals() {
    "use strict";
    animSpeed = $('#speed').val();
    animDelay = $('#delay').val();
}

function resetPosition() {
    "use strict";
    $('li').stop().css('margin-top', 0);
    id = 0;
    working = 0;
    $('#toggle').html('Show &darr;');
}

$(function () {
    "use strict";
    $('header > a').click(function () {
        if (id === 0 && working === 0) {
            getVals();
            items = $('ul').children().length;
            var z;
            for (z = 0; z < items; z++) {
                $('li').eq(z).css('z-index', items - z);
            }
            working = 1;
            rollDown(items, id);
        } else if (id !== 0) {
            resetPosition();
            alert('!!');
        }
        return false;
    });
});

以下是我的控制台打印出来的内容:

items: 6 & id: 0
id: 0
-----
animSpeed: 410
-----
animDelay: 20
-----
working: 1
==============
items: 6 & id: 1
id: 0
-----
animSpeed: 410
-----
animDelay: 20
-----
working: 1
==============
items: 6 & id: 2
id: 0
-----
animSpeed: 410
-----
animDelay: 20
-----
working: 1
==============
items: 6 & id: 3
id: 0
-----
animSpeed: 410
-----
animDelay: 20
-----
working: 1
==============
items: 6 & id: 4
id: 0
-----
animSpeed: 410
-----
animDelay: 20
-----
working: 1
==============
items: 6 & id: 5
id: 0
-----
animSpeed: 410
-----
animDelay: 20
-----
working: 1
==============
items: 6 & id: 6
id: 0
-----
animSpeed: 410
-----
animDelay: 20
-----
working: 1
==============
items: 6 & id: 7
herp derp
id: 0
-----
animSpeed: 410
-----
animDelay: 20
-----
working: 1
==============

2 个答案:

答案 0 :(得分:4)

您有id作为rollDown方法签名中定义的参数。如果删除它,您的全局变量将正确更新。

发件人:

function rollDown(items, id) {

function rollDown(items) {

您可能还想删除items,因为它也在全局命名空间中定义。

答案 1 :(得分:0)

当你输入名称为id的函数变量时,如{:1}},你将遍历全局变量。

使用:

function rollDown(items, id)