简体   繁体   English

单击按钮时执行不同的功能

[英]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): 目前我正在这样做(也是一个演示来说明我的意思):

CodePen.io 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. 基本上我使用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) 我能想到的另一种方法是使用一个包含所有文本的数组 ,我的函数只需要通过它(看起来效率更高)


  • But I still want to know if there is any other way out there (though obvious) that you can achieve this with pure Javascript. 但我仍然想知道是否有任何其他方法(虽然显而易见)你可以用纯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 ++
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 单击传单弹出窗口中的按钮时,显示执行功能的问题 - Problem to display to execute a function when clicking on a button inside a leaflet popup 单击 GoogleDoc 侧边栏上的按钮时,我需要执行一个函数() - I need to execute a function() when clicking a button on GoogleDoc sidebar 如何在不单击按钮的情况下执行此功能 - How to execute this function without clicking on a button PHP:单击按钮时执行函数 - PHP: execute function upon clicking a button 单击后执行jQuery函数 - Execute jQuery function after clicking <button> 按下回车键或单击按钮时如何创建一个按钮来执行代码? - How to Create a button to execute code when pressing enter or clicking the button? 如何在单击输入按钮时提交表单以及执行javascript函数? - How to submit a form as well as execute a javascript function in clicking an input button? 在点击 sweetalert 弹出按钮后执行 PHP function - Execute a PHP function after clicking on sweetalert popup button 在通常通过单击按钮执行的站点上执行 function - Execute a function on a site which is normally executed by clicking a button 如何通过单击HTML按钮执行JavaScript函数? - How do I execute a JavaScript function from clicking an HTML button?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM