全局变量不't随jquery函数变化

Global variable doesn't change with jquery function

本文关键字:jquery 函数 变化 全局变量      更新时间:2023-09-26

我的代码有问题。因此,我试图将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;
}

您应该尝试使用回调:

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