Javascript / jQuery switch语句使用静态定义的变量

时间:2013-12-13 02:27:05

标签: javascript jquery

我正在尝试编写一个切换视频图片的脚本,但是在我的情况下切换似乎不起作用而且我在javascript上很糟糕。我只想在页面加载时设置vid=1;并使用点击事件循环浏览我的选项。我哪里做错了?我正在尝试使用此示例来使用:switch statement in Jquery and List

我的代码:

$(function(){
  var vid=1;
  $('#next-vid').click(function(){
      switch (vid) { 
        case '1': 
            $('#vid1').hide();
            $('#vid2').show();
            $('#vid3').hide();
            $('#vid4').hide();
            vid=2;
            break;
        case '2': 
            $('#vid1').hide();
            $('#vid2').hide();
            $('#vid3').show();
            $('#vid4').hide();
            vid=3;    
            break;
        case '3':
            $('#vid1').hide();
            $('#vid2').hide();
            $('#vid3').hide();
            $('#vid4').show();
            vid=4;  
            break;
        case '4': 
            $('#vid1').show();
            $('#vid2').hide();
            $('#vid3').hide();
            $('#vid4').hide();
            vid=1;  
            break;
    }
  });
  $('#prev-vid').click(function(){
      switch (vid) { 
        case '1': 
            $('#vid1').hide();
            $('#vid2').hide();
            $('#vid3').hide();
            $('#vid4').show();
            vid=4;
            break;
        case '2': 
            $('#vid1').show();
            $('#vid2').hide();
            $('#vid3').hide();
            $('#vid4').hide();
            vid=1;    
            break;
        case '3':
            $('#vid1').hide();
            $('#vid2').show();
            $('#vid3').hide();
            $('#vid4').show();
            vid=2;  
            break;
        case '4': 
            $('#vid1').hide();
            $('#vid2').hide();
            $('#vid3').show();
            $('#vid4').hide();
            vid=3;  
            break;
    }
  });

});

2 个答案:

答案 0 :(得分:4)

呃...这可能更简单。

$(function() {
    var vid = 0;
    $("#next-vid").click(function() {
        vid = (vid + 1) % 4;
        $("[id^=vid]").hide();
        $("#vid"+(vid+1)).show();
    });
    $("#prev-vid").click(function() {
        vid = (vid + 3) % 4;
        $("[id^=vid]").hide();
        $("#vid"+(vid+1)).show();
    });
});

答案 1 :(得分:1)

不需要开关。

http://jsfiddle.net/MNe57/1/

var vid=1;
$('#next-vid').click(function(){
    vid = vid === 4 ? 1 : vid+1;
    $('[id^="vid"]').hide();
    $('#vid'+vid).show();
});
$('#prev-vid').click(function(){
    vid = vid === 1 ? 4 : vid-1;
    $('[id^="vid"]').hide();
    $('#vid'+vid).show();
});