0

我在谷歌上下搜索并没有找到一个简单的解决方案。

这是我的代码的 jist:

  var theArray = ["one","two","three","four"];


  $('.next').click(function(){
   // go forward on the array
  })

  $('.back').click(function(){
   // do backwards on the array from the current position
  })

所以,如果用户点击"<button class="next">我会收到“一”的警报,他们再次点击“下一步”,“二”的警报,等等......

有没有快速的方法来做到这一点?

4

2 回答 2

5

当然:

theArray.push(theItem = theArray.shift());
// and...
theArray.unshift(theItem = theArray.pop());

theItem分别是第一项和最后一项。重复调用该函数将继续循环这些项目。

但是请注意,您不能再执行“在末尾添加另一个”之类的操作了。为此,您需要手动跟踪“当前项目”,并对其进行递增/递减,而不是循环使用这些项目。

于 2012-10-18T16:44:29.130 回答
4

您需要第二个变量来跟踪您的索引:

var theArray = ["one","two","three","four"]; 
var arrayIndex=0;

      $('.next').click(function(){
         arrayIndex++
         if(arrayIndex>=theArray.length)
              arrayIndex=0;
         alert(theArray[arrayIndex]);   
      })

      $('.back').click(function(){
         arrayIndex--
         if(arrayIndex<0)
              arrayIndex=theArray.length-1;
         alert(theArray[arrayIndex]);   
      })
于 2012-10-18T16:45:14.133 回答