简体   繁体   English

显示数组的下一个/上一个项目

[英]Show Next/Previous item of an array

I'm writing the first item of an array to the screen, and would like to create Next/Previous buttons for array, but I can't get it to work. 我正在将一个数组的第一项写入屏幕,并希望为数组创建Next/Previous按钮,但我无法使其工作。 I have tried several methods, but I can't find suitable solution. 我尝试了几种方法,但我找不到合适的解决方案。

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>

Say you have an Array var arr = ['foo', 'bar', 'baz']; 假设你有一个数组 var arr = ['foo', 'bar', 'baz']; .
If you want to dynamically choose items from this Array , you'll need a new variable. 如果要从此Array中动态选择项目,则需要一个新变量。 Let's call this i and give it a default value var i = 0; 我们称之为i并给它一个默认值var i = 0;

So far, arr[i]; // "foo" (i === 0) 到目前为止, 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 . 现在,让我们编写一个函数,通过修改i来选择下一个项目。 We may want to consider what we want to happen when i is bigger than (or equal to) arr.length as well. 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.write is nearly always a bad idea. 首先要注意的是document.write几乎总是一个坏主意。 Instead, why not give our Elements some unique id attributes and use DOM methods in JavaScript after the Elements exist . 相反,为什么不在Elements存在之后给我们的Elements一些唯一的 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 JavaScript as document.getElementById('output') , and the two <span> s similarly. 所以现在我们可以访问JavaScript中的第一个<div>作为document.getElementById('output') ,两个<span>类似。

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 listeners to the <span> s so they perform an action. 接下来,我们需要向<span>添加事件侦听器 ,以便它们执行操作。 The handler of each will set the text of the <div> in a similar way to above, but using the relevant function from earlier. 每个处理程序将以与上面类似的方式设置<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 Elements exist". 现在唯一要做的就是确保它“在元素存在之后”运行。 There are two ways to do this, either by putting the <script> element after the elements it uses, or by listening for the load event on window, ie 有两种方法可以做到这一点,方法是将<script>元素放在它使用的元素之后,或者通过在窗口上监听load事件 ,即

window.addEventListener('load', function () {
    // DOM related JavaScript goes here
});

DEMO of 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. 如果您想多次执行此操作或将其与其他JavaScript混合使用 ,则可能需要考虑变量名称冲突。 The easiest way to get around this is by using an IIFE to create a "safe place" for your variables, but this answer is already long enough. 解决这个问题的最简单方法是使用IIFE为变量创建一个“安全的地方”,但这个答案已经足够长了。

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>

Try this way, easier and corrected. 尝试这种方式,更容易和纠正。 -Alfa College Application Developer. -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>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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