我无法弄清楚如何点击数组

时间:2012-10-18 16:42:23

标签: javascript jquery

我在google上搜索过,并没有找到一个简单的解决方案。

以下是我的代码的主旨:

  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">我会收到“一个”的提示,他们会再次点击“下一个”,提醒“两个”,等等......

有快速的方法吗?

2 个答案:

答案 0 :(得分:5)

不确定

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

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

但是请注意,你不能再做“添加到另一端”之类的事了。要做到这一点,你需要手动跟踪“当前项目”,并递增/递减它而不是循环项目。

答案 1 :(得分: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]);   
      })