[英]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. 我正在使用Javascript开发一个网页,我想实现一个按钮,这样每当你点击它时,按钮内的文字就会变成下一个文本。
Currently I'm doing it like this (also a demo to illustrate what I mean): 目前我正在这样做(也是一个演示来说明我的意思):
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. 基本上我使用switch语句和计数器一步一步走。
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) 我能想到的另一种方法是使用一个包含所有文本的数组 ,我的函数只需要通过它(看起来效率更高)
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 ++
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.