更新全局变量

时间:2012-10-26 20:16:24

标签: jquery

我需要一些帮助。我正在尝试使用我自己的内容滑块编写自己的代码,但似乎无法解决这个问题。我很新,并且学习这一切,所以任何帮助都会受到赞赏。我要做的是当用户点击下一步时,它将隐藏当前幻灯片并显示下一张幻灯片。我试图用全局变量做这个,但我不确定如何维护从函数内更新的全局变量。这是一些代码,我知道我的解释不是很好。

$(function () {


    var i = '';

    $('.next').click(function() {
        $('.slide' + i).hide();
        i++;
        console.log(i);
        if(i <= 4) {
        $('.slide' + i).show();
        }
        else {
        var i = 1;
        $('.slide' + i).show();
        i++;
        console.log(i);
        }
    });

});

和标记

<div class="outerWrapper wrapperWidthHeight">
    <div class="innerWrapper wrapperWidthHeight slide1">
    1
    </div>
    <div class="innerWrapper wrapperWidthHeight slide2">
    2
    </div>
    <div class="innerWrapper wrapperWidthHeight slide3">
    3
    </div>
    <div class="innerWrapper wrapperWidthHeight slide4">
    4
    </div>
</div>
<div class="next">NEXT</div>

和CSS

.wrapperWidthHeight {
    margin:auto;
    width:900px;
    height:600px;
    }

.outerWrapper {
    overflow:hidden;
    position:relative;
    margin-top:10px;
    border:1px solid black;
    border-radius:15px;
    box-shadow: 2px 2px 5px 5px #888;
    }

.innerWrapper {
    position:absolute;
    text-align:center;
    padding:0;
    margin:auto;
    }


.slide1 {
    display:block;
    }

.slide2, .slide3, .slide4 {
    display:none;
    }

.next{
    display:block;
    margin:auto;
    }

3 个答案:

答案 0 :(得分:1)

只是对你为我工作的东西做了一些调整:

$(document).ready(function () {

    var i = 1;

    $('.next').click(function () {
        $('.slide' + i).hide();
        i++;
        console.log(i);
        if (i <= 4) {
            $('.slide' + i).show();
        }
        else {
            i = 1;
            $('.slide' + i).show();
            console.log(i);
        }
    });

});

答案 1 :(得分:1)

$(function () {

    var i = 1;   // should be a number
    // this var IS NOT global, nut it is available to
    // the scope of the anonymous function

    $('.next').click(function() {
        // accessing i here is only accessing via
        // the scope chain, i isn't "global" this way

        $('.slide' + i).hide();
        i++;
        console.log(i);

        if(i > 4) {
           i = 1;  // DON'T write "var" here, doing so
                   // defines a NEW local variable i in the local scope
        }

        $('.slide' + i).show();
        // you don't need to increment i here,
        // it's already incremented by setting from 4+ to 1
        console.log(i);
    });
});​

答案 2 :(得分:0)

尝试在函数外部创建全局变量作为窗口对象的成员。 你可以把这样的东西放在你的功能之外:

window.i = 0;

如果你要增加它,你也应该将它初始化为零,而不是空字符串,我不是说它会导致问题,只是这是一个好习惯。

相关问题