全局变量不会随jquery函数而改变

时间:2013-08-29 09:36:52

标签: javascript jquery

我的代码有问题。所以我试图将interval的值从9更改为current_interval的值。这通过点击事件发生。但是当ChangePicture()函数启动时间隔仍然是9(基本上我有一个图片旋转脚本,在5秒后改变图片)。

var interval = 9;
var globalCounter = 0;
var temp = setInterval(function() {ChangePicture()}, 5000);


function SetInterval(i)
{
    interval = i;
}

$(document).on("click", ".picture_button_lol", function(event){
    var current_interval    = $(this).children(".amount_of_pictures").val();
    SetInterval(current_interval);

});

function ChangePicture()
{
    var pictureId = globalCounter%interval;
    ShowAndHide(pictureId);
    globalCounter = globalCounter + 1;
}

function ShowAndHide(picId)
{
    var picture = "bigview_" + picId;
    var text    = "bigview_text_" + picId;
    var button  = "bigview_button_" + picId;
    var z_index = 1;

    document.getElementById(picture).style.zIndex   = z_index;
    document.getElementById(text).style.zIndex      = z_index;
    document.getElementById(button).style.backgroundColor = "#ffffff";
    document.write(interval);
    for(var i=0; i<interval; i++)
    {
        if(i != picId)
        {
            picture = "bigview_" + i;
            text    = "bigview_text_" + i;
            button  = "bigview_button_" + i;
            z_index = 0;

            document.getElementById(picture).style.zIndex   = z_index;
            document.getElementById(text).style.zIndex      = z_index;
            document.getElementById(button).style.backgroundColor = "#000000";
        }
    }

    globalCounter = picId;
}

1 个答案:

答案 0 :(得分:0)

你应该尝试使用回调:

function ChangePicture()
{
    var pictureId = globalCounter%interval;
    ShowAndHide(pictureId, function() {
        globalCounter = globalCounter + 1;
    });    
}

function ShowAndHide(picId, callback)
{
    var picture = "bigview_" + picId;
    var text    = "bigview_text_" + picId;
    var button  = "bigview_button_" + picId;
    var z_index = 1;

    document.getElementById(picture).style.zIndex   = z_index;
    document.getElementById(text).style.zIndex      = z_index;
    document.getElementById(button).style.backgroundColor = "#ffffff";
    document.write(interval);
    for(var i=0; i<interval; i++)
    {
        if(i != picId)
        {
            picture = "bigview_" + i;
            text    = "bigview_text_" + i;
            button  = "bigview_button_" + i;
            z_index = 0;

            document.getElementById(picture).style.zIndex   = z_index;
            document.getElementById(text).style.zIndex      = z_index;
            document.getElementById(button).style.backgroundColor = "#000000";
        }
    }

    globalCounter = picId;
    callback();
}