简体   繁体   中英

Issue with Revealing Individual Images & Ending Loop

Since my last question, I've decided to reveal images individually. However, now I'm having an issue with the sequence. With what I've written so far, it seems that my second needed image (stack2.PNG) appears before the first (stack1.PNG). Also, I'm not too sure how to go about ending the function after the final image (stack3.PNG).

Here's what I have so far:

<body>

<input type=button value="Produce Stipends" onclick="nextStack()"/>
<img id="stipends" src="nostack.PNG">

</body>
<script>

  var stipends = document.getElementById("stipends");
  var stack = ["stack1.PNG", "stack2.PNG", "stack3.PNG"];
  var currentStack = 0;

  stack.forEach(function(src) {
    new Image().src = src;
    });
    
  function nextStack() {
    currentStack++;
    currentStack > 2 && (currentStack = 0);
    stipends.src = stack[currentStack];
    }

</script>

Also, if it's not too much to ask, how would I go about changing the name of the button once the sequence is over and linking to another page.

Thanks in advance!

Run the below code if you want to output a single index of the stack array on each click.

EDIT: Included comments in code.

 var stipends = document.getElementById("stipends"); var stack = ["stack1.PNG", "stack2.PNG", "stack3.PNG"]; //currentStack = 0 starts the index at 0 //we will use this to iterate over the array in sequential order starting with the first item var currentStack = 0; function nextStack() { //declare array length as a var var len = stack.length; //on click, check if currentStack value is less than len if(currentStack < len){ //console log the item in the stack array that has a matching index console.log(stack[currentStack]); //apply the same output as image source stipends.src = stack[currentStack]; //continue adding to the currentStack for the next loop until finished currentStack++; } }
 <input type=button value="Produce Stipends" onclick="nextStack()" /> <img id="stipends" src="nostack.PNG">

Is this what you're trying to do?

 var stipends = document.getElementById("stipends"); var stack = ["stack1.PNG", "stack2.PNG", "stack3.PNG"]; var currentStack = 0; function nextStack() { currentStack++; stipends.src = stack[currentStack]; if (currentStack > stack.length) { currentStack = 0; } }
 <input type="button" value="Produce Stipends" onclick="nextStack()"/> <img id="stipends" src="nostack.PNG">

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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