连续循环遍历 JavaScript 文本数组 onclick
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/7843467/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Continuously loop through JavaScript text array onclick
提问by Staysee
I have a text array. I want to display the first entry on page load. And then replace the text with the next entry when I click a button. If I keep clicking the button I want the text to continuously be replaced by waht is next in the array, and when it gets to the end start back at the first entry. Can someone please show me an example code for that. I am new to this.
我有一个文本数组。我想在页面加载时显示第一个条目。然后当我单击一个按钮时用下一个条目替换文本。如果我一直单击按钮,我希望文本不断被替换为 waht 是数组中的下一个,当它到达末尾时从第一个条目开始。有人可以给我看一个示例代码。我是新来的。
Here's what I have
这是我所拥有的
$(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]);
}
});
});
回答by RobG
Something like the following should do the trick:
像下面这样的东西应该可以解决问题:
<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"> </p>
<button onclick="
document.getElementById('foo').innerHTML = nextWord();
">Update</button>
Edit
编辑
Radomised version:
辐射化版本:
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);
}
}());
回答by Juan Mendes
The following should do it http://jsfiddle.net/mendesjuan/9jERn/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 ;
});
});
Your code was writing all three values each time you clicked it (but only displaying that last value)
每次单击时,您的代码都会写入所有三个值(但只显示最后一个值)
回答by Terhands
I think something like this would work
我认为这样的事情会奏效
The javascript would look like:
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];
}
The html would look like:
html 看起来像:
<body onLoad=nextElement()>
...
<elementToDisplayText id=textDisplay></elementToDisplayText>
<button onClick=nextElement()>Next</button>