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

javascript - Show NextPrevious item of an array - Stack Overflow

programmeradmin1浏览0评论

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. 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>

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. 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>
Share Improve this question edited Nov 15, 2014 at 13:13 Alex Kulinkovich 4,77815 gold badges49 silver badges54 bronze badges asked Nov 15, 2014 at 10:47 dodododo 4792 gold badges9 silver badges23 bronze badges 3
  • Can you alaborate? why are you using anchors for this? write a function for handling onClick event and do whatever you want to do in it – Ahmed Commented Nov 15, 2014 at 10:50
  • 5 What do you expect javascript: sav[i++] does? – Jonathan Commented Nov 15, 2014 at 10:50
  • 1 One more example: jsfiddle.net/7mzzep4m – dfsq Commented Nov 15, 2014 at 11:08
Add a comment  | 

3 Answers 3

Reset to default 31

Say you have an Array var arr = ['foo', 'bar', 'baz'];.
If you want to dynamically choose items from this Array, you'll need a new variable. Let's call this i and give it a default value var i = 0;

So far, 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 i is bigger than (or equal to) arr.length as well.

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

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

First thing to note is that document.write is nearly always a bad idea. Instead, why not give our Elements some unique id attributes and use DOM methods in JavaScript after the Elements exist.

<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.

Now, let's set the initial text in the <div>, this is quite easy

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. The handler of each will set the text of the <div> in a similar way to above, but using the relevant function from earlier.

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, i.e.

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. 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.

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.

<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>
发布评论

评论列表(0)

  1. 暂无评论