连续循环通过JavaScript文本数组onclick

Continuously loop through JavaScript text array onclick

本文关键字:文本 数组 onclick JavaScript 循环 连续      更新时间:2023-09-26

我有一个文本数组。我想在页面加载时显示第一个条目。然后,当我单击按钮时,用下一个条目替换文本。如果我继续单击按钮,我希望文本连续地被数组中的下一个内容所替换,并且当它到达结束时,从第一个条目开始。有人能告诉我一个例子代码。我是新手。

这是我的

$(document).ready(function(){
  var arr = new Array("One","Two","Three");
  var len=arr.length;
  $('#next').click(function(){ 
    for(var i=0; i<len; i++) { 
      $('#quote').html(arr[i]); 
    } 
 });
});

应该像下面这样做:

<script type="text/javascript">
var nextWord = (function() {
  var wordArray = ['fe','fi','fo','fum'];
  var count = -1;
  return function() {
    return wordArray[++count % wordArray.length];
  }
}());
</script>
<p id="foo">&nbsp;</p>
<button onclick="
  document.getElementById('foo').innerHTML = nextWord();
">Update</button>

编辑

Radomised版本:

var nextWord = (function() {
  var wordArray = ['fe','fi','fo','fum'];
  var copy;
  return function() {
    if (!copy || !copy.length) copy = wordArray.slice();
    return copy.splice(Math.random() * copy.length | 0, 1);
  }
}());

应该这样做http://jsfiddle.net/mendesjuan/9jERn/1

$(document).ready(function(){
  var arr = ["One","Two","Three"];
  var index = 0;
  $('#next').click(function(){ 
    $('#quote').html(arr[index]); 
    index = (index + 1) % arr.length ;
 });
});

每次你点击它的时候,你的代码都在写这三个值(但只显示最后一个值)

我想这样做会有用的

javascript看起来像:

// assuming maxTextArrayIndex & textArray are defined & populated
var textDisplayIndex = -1;
document.getElementById('textDisplay').innerHTML = textArray[textDisplayIndex];
function nextElement()
{
    textDisplayIndex += 1;
    if (textDisplayIndex > maxTextArrayIndex)
    {
        textDisplayIndex = 0;
    }
    document.getElementById('textDisplay').innerHTML = textArray[textDisplayIndex];
}

html看起来像:

<body onLoad=nextElement()>
...
<elementToDisplayText id=textDisplay></elementToDisplayText>
<button onClick=nextElement()>Next</button>