最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Cycle through an array on click - Stack Overflow

programmeradmin3浏览0评论

I am wondering how to cycle through the values in an array on click? When the last value of the array is displayed, then the next click should display the first value of the array again.

I think that I am close, however when I get to the last value of the array I have to click twice before it displays the first value again.

Here is my JavaScript:

var myArray = ["red", "yellow", "green"];
var myIndex = 1;
var print = document.getElementById('print');

print.innerHTML = myArray[0]; //Print first value of array right away.

function nextElement() {
  if (myIndex < myArray.length) {
     print.innerHTML = myArray[myIndex];
     myIndex++;
  }
  else {
     myIndex = 0;   
  }
};

Here is my HTML:

<p>The color is <span id="print"></span>.</p> 

<a id="click" href="#" onclick="nextElement();">Click</a>

Here's a fiddle if that is helpful:

/

I am wondering how to cycle through the values in an array on click? When the last value of the array is displayed, then the next click should display the first value of the array again.

I think that I am close, however when I get to the last value of the array I have to click twice before it displays the first value again.

Here is my JavaScript:

var myArray = ["red", "yellow", "green"];
var myIndex = 1;
var print = document.getElementById('print');

print.innerHTML = myArray[0]; //Print first value of array right away.

function nextElement() {
  if (myIndex < myArray.length) {
     print.innerHTML = myArray[myIndex];
     myIndex++;
  }
  else {
     myIndex = 0;   
  }
};

Here is my HTML:

<p>The color is <span id="print"></span>.</p> 

<a id="click" href="#" onclick="nextElement();">Click</a>

Here's a fiddle if that is helpful:

http://jsfiddle/jBJ3B/

Share Improve this question asked Jun 20, 2013 at 1:11 MddMdd 4,42012 gold badges47 silver badges71 bronze badges
Add a ment  | 

3 Answers 3

Reset to default 12

You could use the modulo operator like this:

function nextElement() {
  print.innerHTML = myArray[myIndex];
  myIndex = (myIndex+1)%(myArray.length);
  }
};

See: http://jsfiddle/jBJ3B/3/

Even more extreme is (as zdyn has written):

function nextElement() {
   print.innerHTML = myArray[myIndex++%myArray.length];
};

See: http://jsfiddle/jBJ3B/5/

As concise as I could get it:

function nextElement() {
  print.innerHTML = myArray[myIndex++ % myArray.length]
}

var print = document.getElementById('print');

why do you assign a variable to this? why not just write

document.getElementById('print').innerHTML = myArray[0]; //Print first value of array right away. document.getElementById('print').style.color = myArray[0]; //Set color of id print.

发布评论

评论列表(0)

  1. 暂无评论