一个HTML按钮可连续调用3个函数

One HTML button to invoke 3 functions consecutively

本文关键字:调用 3个 函数 连续 HTML 按钮 一个      更新时间:2023-09-26

我是Javascript编程的新手,需要一些帮助

我有一个HTML按钮,我想调用3个函数
第一次单击按钮时,我想调用函数1。
下次单击按钮时,我想调用函数2。
第三次单击按钮时,我想调用函数3。

我在想我可以使用if测试
单击按钮时i++
if ( i == 1){ function1(); }

HTML

<button type="button" onclick="myFunction()">Hei</button>

Javascript

if(i == 1){
  test1();
}
if(i == 2){
  test2();
}
if(i == 3){
  test3();
}
function test1() {
  document.getElementById("print1").innerHTML = "test1"; 
}
function test2() {
  document.getElementById("print2").innerHTML = "test2";
}
function test3() {
  document.getElementById("print3").innerHTML = "test3";
}

这只是为了测试/练习,所以代码没有点

但我认为必须有另一种方法。

试试这个:

<button onclick="myFun(i)"></button>

在javascript中,

function myFun(i) {
    (i===0 && function1()) || (i===1 && function2()) || function3();
}
//Html
<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <title>JS Bin</title>
</head>
<body>
  <button onclick="triggerFunc()">Click Me</button>
</body>
</html>
//Javascript
var obj = {
f1: function() {
  alert('from f1');
},
f2: function() {
  alert('from f2');
},
  f3: function() {
  alert('from f3');
}
};
window.flag = 1;
function triggerFunc() {
  var flag  = window.flag + 1;
  if(flag > 3){
    flag = 1;
  }
  window.flag = flag;
  obj['f'+ flag]();
}

只需检查jsbin链接http://jsbin.com/dudubaxafu/edit?html,js,输出

您可以执行以下代码:-

HTML代码:-

<button type="button" onclick="myFunction()">Hei</button>

javascript代码:-

i = 1;
function myFunction()
{
    if (i == 1)
    {
        i++;
        test1();
    }
    else if (i == 2)
    {
        i++;
        test2();
    }
    else if (i == 3)
    {
        i++;
        test3();
    }
}
function test1() {
  document.getElementById("print1").innerHTML = "test1"; 
}
function test2() {
  document.getElementById("print2").innerHTML = "test2";
}
function test3() {
  document.getElementById("print3").innerHTML = "test3";
}

它可能会对你有所帮助。

我不建议通过窗口["I"]污染全局命名空间,因为它限制您只能使用一个这样的按钮。

我会用这样的东西:

function cycle(){
   var i = 0;
   var args = arguments;
   return function(){
      args[i]();
      i++;
      if(i>=args.length)
        i = 0;
      }
 };

那么你可以这样使用它:

document.getElementById("button1").addEventListener("click", cycle(
 function(){
 alert(1);
},
function(){
 alert(2);
},
 function(){
 alert(3);
}));

这是一个小提琴样品:https://jsfiddle.net/h6qsam8e/