简体   繁体   中英

I can't figure out how to click through an array

I've searched up and down google and haven't found a simple solution.

Here is the jist of my code:

  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
  })

so, if the user clicks on "<button class="next"> I would get an alert of "one", they click on "next" again, an alert of "two", etc...

Is there a quick way to do this?

Sure:

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

theItem is the first and last item respectively. Repeated calling of the function will continue cycling the items.

However note that you can't do something like "add another to the end" anymore. To get that, you will need to manually keep track of the "current item", and increment/decrement it instead of cycling the items around.

You'll need a second variable to keep track of your index:

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]);   
      })

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM