简体   繁体   中英

Javascript function continues a step longer than needed

I have a function that continues one step longer than needed. When the image (elefant.png) is clicked the image (scale1.png) is changed. There are 5 pictures and it works fine. Problem is that when the last picture is displayed, and I click (elefant.png) again it comes to an undefined picture? I don't understand why it doesn't just stop on the last picture (scale5.png)?

<!DOCTYPE html>
<html lang="en" dir="ltr">
  <head>
    <meta charset="utf-8">
    <title></title>
  </head>
  <link rel="stylesheet" href="style.css">
  <body>

    <div class="wrapper1">

      <h2 id="title_text">Hey</h2>

        <img src="image/scale1.png" id="getImage">

        <img src="image/elefant.png" style="width:250px; height:auto;" onclick="imagefun()">



    </div>

    <script type="text/javascript">

        var counter = 0,
    gallery = ["image/scale2.png", "image/scale3.png", "image/scale4.png", "image/scale5.png"],
    imagefun = function () {
        document.getElementById("getImage").src = gallery[counter];
        counter++;
        if (counter >= 4) {
            document.getElementById("title_text").innerHTML = "New text!";
        }

    };

    </script>


  </body>
</html>

This might be an easy fix, but I am not good with javascript. I tried searching for an answer but I'm not sure what to even look for as I don't know what causes the issue?

I'm not exactly sure what your end result should be once you hit the end of your gallery array but as it stands it changes title_text to "New text!".

The problem with your code as it stands is you always increment counter and change the source getImage based on that integer. That doesn't stop once your counter hits 4.

I'd use the array length as a stopping point and only increment the counter variable up until that limit is hit. I would write something like this:

 var counter = 0, gallery = ["image/scale2.png", "image/scale3.png", "image/scale4.png", "image/scale5.png"], imagefun = function () { if (counter >= gallery.length) { document.getElementById("title_text").innerHTML = "New text!"; } else{ document.getElementById("getImage").src = gallery[counter]; counter++; } };
 <div class="wrapper1"> <h2 id="title_text">Hey</h2> <img src="image/scale1.png" id="getImage"> <img src="image/elefant.png" style="width:250px; height:auto;" onclick="imagefun()"> </div>

You always run the function and change the image source, and only then check for counter 's value. That's why it'll keep going and changing the source even when counter is bigger than 3.

A solution would be to change counter ' s value conditionally:

if (counter < gallery.length - 1) {
  counter++;
} 

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