简体   繁体   中英

Execute different function when clicking on button

I'm working on a webpage using Javascript and I want to implement a button so that whenever you click it the text inside the button change to the next text.

Currently I'm doing it like this (also a demo to illustrate what I mean):

CodePen.io

var textCount = 0;
function changeText() {
  var myText = document.getElementById("demo");
  switch (textCount) {
    case 0:{
      myText.innerHTML = "This is the second text";
      textCount++;
    }
    break;
    case 1: {
      myText.innerHTML = "This is the third text";
      textCount++;
    }
    break;
    case 2: {
      myText.innerHTML = "It keeps going on like this";
      textCount++;
    }
    break;
  }
}

Basically I use the switch statement and a counter to go step by step.

Another way I can think of to do this is by having an array that holds all the text and my function just go through it (seems more efficient)


  • But I still want to know if there is any other way out there (though obvious) that you can achieve this with pure Javascript.

Thanks in advance.

You are correct, you can make it cleaner & more efficient by using an array, for example:

let list = ['Message one', 'Message two', 'Message three', 'Message four'];

let counter = 0;

function clickHandler () {
    element.textContent = list[counter];
    counter = (counter + 1) % list.length; // If you want to loop messages, otherwise ++
}

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