Javascript 显示数组的下一个/上一个项目
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/26944987/
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
Show Next/Previous item of an array
提问by Jancsik Zsolt
I'm writing the first item of an array to the screen, and would like to create Next/Previousbuttons for array, but I can't get it to work. I have tried several methods, but I can't find suitable solution.
我正在将数组的第一项写入屏幕,并想Next/Previous为数组创建按钮,但我无法让它工作。我尝试了多种方法,但找不到合适的解决方案。
Can anyone help?
任何人都可以帮忙吗?
This is the last one I have tried:
这是我尝试过的最后一个:
<div>
<script type="text/javascript">
sav = new Array(
"first item",
"second item",
"third item",
);
document.write(sav[0] + " <br>");
</script>
</div>
<div>
<a href="" onClick="javascript: sav[i++]">Previous</a>
<a href="" onClick="javascript: sav[i--]">Next!</a>
</div>
回答by Paul S.
Say you have an Arrayvar arr = ['foo', 'bar', 'baz'];.
If you want to dynamically choose items from this Array, you'll need a new variable. Let's call this iand give it a default value var i = 0;
假设你有一个Arrayvar arr = ['foo', 'bar', 'baz'];。
如果要从此Array动态选择项目,则需要一个新变量。让我们调用它i并给它一个默认值var i = 0;
So far, arr[i]; // "foo" (i === 0)
迄今为止, arr[i]; // "foo" (i === 0)
Next and Previous
下一个和上一个
Now, lets write a function to choose the next item by modifying i. We may want to consider what we want to happen when iis bigger than (or equal to) arr.lengthas well.
现在,让我们编写一个函数来通过修改i. 我们可能还想考虑当i大于(或等于)时我们想要发生什么arr.length。
function nextItem() {
i = i + 1; // increase i by one
i = i % arr.length; // if we've gone too high, start from `0` again
return arr[i]; // give us back the item of where we are now
}
Next, lets do the reverse, this time we might want to consider what should happen for negative i
接下来,让我们反过来做,这一次我们可能要考虑负数应该发生什么 i
function prevItem() {
if (i === 0) { // i would become 0
i = arr.length; // so put it at the other end of the array
}
i = i - 1; // decrease by one
return arr[i]; // give us back the item of where we are now
}
So far,
迄今为止,
nextItem(); // "bar" (i === 1)
prevItem(); // "foo" (i === 0 as we did `0 + 1 - 1`)
// also
prevItem(); // "baz" (decreased on 0)
nextItem(); // "foo" (increased at end of arr)
Great, so we've got the basic algorithms down.
太好了,我们已经掌握了基本算法。
Connecting this to the DOM
将此连接到DOM
First thing to note is that document.writeis nearly always a bad idea. Instead, why not give our Elementssome uniqueid attributesand use DOMmethods in JavaScriptafter the Elementsexist.
首先要注意的是,这document.write几乎总是一个坏主意。相反,为什么不给我们的元素一些独特的id 属性,并在元素存在后在JavaScript 中使用DOM方法。
<div id="output"></div>
<div>
<span id="prev_button">Previous</span>
<span id="next_button">Next!</span>
</div>
So now we can access the first <div>in JavaScriptas document.getElementById('output'), and the two <span>s similarly.
所以现在我们可以<div>在JavaScript 中访问第一个as document.getElementById('output'),两个<span>s 类似。
Now, let's set the initial text in the <div>, this is quite easy
现在,让我们在 中设置初始文本<div>,这很容易
document.getElementById('output').textContent = arr[0]; // initial value
// if i is still at it's default value, we could have used i instead of 0
Next, we need to add event listenersto the <span>s so they perform an action. The handler of each will set the text of the <div>in a similar way to above, but using the relevant functionfrom earlier.
接下来,我们需要向s添加事件侦听器,<span>以便它们执行操作。每个的处理程序将以<div>与上面类似的方式设置 的文本,但使用之前的相关函数。
document.getElementById('prev_button').addEventListener(
'click', // we want to listen for a click
function (e) { // the e here is the event itself
document.getElementById('output').textContent = prevItem();
}
);
document.getElementById('next_button').addEventListener(
'click', // we want to listen for a click
function (e) { // the e here is the event itself
document.getElementById('output').textContent = nextItem();
}
);
This is great! Now the only thing left to do is make sure it runs "after the Elementsexist". There are two ways to do this, either by putting the <script>element after the elements it uses, or by listening for the load eventon window, i.e.
这很棒!现在唯一要做的就是确保它“在元素存在之后”运行。有两种方法可以做到这一点,要么将<script>元素放在它使用的元素之后,要么通过侦听窗口上的加载事件,即
window.addEventListener('load', function () {
// DOM related JavaScript goes here
});
DEMOof everything together
一起演示所有内容
If you want to do this multiple times or are mixing it with other JavaScript, you may need to consider variable name conflicts. The easiest way to get around this is by using an IIFEto create a "safe place" for your variables, but this answer is already long enough.
如果您想多次执行此操作或将其与其他JavaScript混合使用,则可能需要考虑变量名冲突。解决这个问题的最简单方法是使用IIFE为您的变量创建一个“安全的地方”,但这个答案已经足够长了。
回答by DOTNET Team
Try this way easier and corrected.
尝试这种方式更容易和更正。
<script type="text/javascript">
var text = [
"first item",
"second item",
"third item"
];
var Current = 0;
document.getElementById("textHere").innerHTML = text[Current];
function Prev(){
if(Current == 0){
Current = text.length - 1;}
else{
Current--;}
document.getElementById("textHere").innerHTML = text[Current];
}
function Next(){
if(Current == text.length - 1){
Current = 0}
else{
Current++;}
document.getElementById("textHere").innerHTML = text[Current];
}
</script>
<div id="textHere"></div>
<div>
<button onclick="Next();">Next!</button>
<button onclick="Prev();">Previous</button>
</div>
回答by Gumpy
Try this way, easier and corrected. -Alfa College Application Developer.
尝试这种方式,更容易和更正。-阿尔法学院应用程序开发人员。
<script type="text/javascript">
var text = [
"first item",
"second item",
"third item"
];
var Current = 0;
document.getElementById("textHere").innerHTML = text[Current];
function Prev(){
if(Current == 0){
Current = text.length - 1;}
else{
Current--;}
document.getElementById("textHere").innerHTML = text[Current];
}
function Next(){
if(Current == text.length - 1){
Current = 0}
else{
Current++;}
document.getElementById("textHere").innerHTML = text[Current];
}
</script>
<div id="textHere"></div>
<div>
<button onclick="Next();">Next!</button>
<button onclick="Prev();">Previous</button>
</div>

