j查询使用引用变量

jquery using reference variable

本文关键字:引用 变量 查询      更新时间:2023-09-26

我引用的变量不断重置为 0,为什么?每个部分都有一组"上一个"和"下一个"按钮,最初它们工作正常,但是当我返回到某个部分时,该部分的计数器设置为 0。它应保留以前设置的数字。提前谢谢。这不是正在使用的实际代码,但它演示了问题(我希望)

var currentPageIndex = null;
var section1_count = 0;
var section2_count = 0;
var section3_count = 0;
function checkSectionPage( value ){
    switch(value){
        case "section1":
            currentPageIndex= section1_count;
            break;
        case "section2":
            currentPageIndex= section2_count;
            break;
        case "section3":
            currentPageIndex= section3_count;
            break;
    }
}
$('.slidePrevious').click(function(){
    checkSectionPage($(this).parent().attr('id'));
    currentPageIndex--;
});
$('.slideNext').click(function(){
    checkSectionPage($(this).parent().attr('id'));
    currentPageIndex++;
});

你永远不会更新部分#_count。将currentPageIndex设置为该部分时,部分编号不会增加。您需要手动更新它。

做这样的事情:

var activeSection = "section1";
var sects = {
    "section1" : 0,
    "section2" : 0,
    "section3" : 0
};
$('.slidePrevious').click(function(){
    sects[$(this).parent().attr('id')]--;
});
$('.slideNext').click(function(){
    sects[$(this).parent().attr('id')]--;
});

你不是在增加/减少你认为你是什么。
你想要这样的东西:

currentPageIndex = "section1_count";
 ...
window[currentPageIndex]++;

(浏览器上下文中的裸变量,"全局变量"实际上是window对象中的字段)

或者将计数移动到对象(如@pascarello的答案)或数组中,如下所示:

var pageIndexes = [ 0, 0, 0 ];
which = 1;
 ...
pageIndexes[which]++;