Home > Enterprise >  I'm trying to make a test html where pressing a button moves along the index of an array which
I'm trying to make a test html where pressing a button moves along the index of an array which

Time:02-28

When I test this code it only shows 0, despite the button function running. What have I done wrong? Since I'm only starting out with JavaScript I'd appreciate an in-depth answer.

var y = 1;
myFunction();

function myFunc() {
  var z = 1
  var x = y   z;
  y = x
  alert("f");
}

function myFunction() {
  y = 0;
  alert("sdrz");
}
const numbers = ["0", "1", "2", "3"];
document.getElementById("demo").innerHTML = numbers[y];
<p id="demo"></p>

<button onclick="myFunc()"> 1</button>

CodePudding user response:

Aside from a bunch of other style issues, your innerHTML assignment was not in the onclick, "myFunc" handler, so it was never getting executed. Also your function will exceed the array limits if clicked on too many times.

<!DOCTYPE html>
<html>
  <body >
   <p id="demo"></p>
   <button onclick="myFunc()"> 1</button>
   <script>
   const numbers = ["0", "1", "2", "3"];
   var y=0;

   function myFunc() {
     document.getElementById("demo").innerHTML = numbers[y];
     y  ;
   }

   </script>    
  </body>
</html>
  • Related