如何在函数之间切换

How to do toggle between functions?

本文关键字:之间 函数      更新时间:2023-09-26
HTML
<button type="button" class="btn" name="showAllBtn" onClick="showAllSteps()">Show all</button>
JS
function showAllSteps()
{
//code  
}
function nextStep()
{
//code
}

如果我单击全部显示按钮,它应该在这两个功能之间切换。谁能帮我?

您可以通过使用 dataset 来存储单击状态来做到这一点,

document.querySelector("button[name='showAllBtn']").addEventListener("click",function(){
  var state = this.dataset.clicked;
  state = state || true;
  ((state) ? showAllSteps : nextStep)();
  this.dataset.clicked = !state;  
},false);

编辑:True/false似乎会导致上述代码出现问题。因此,我在上面做了一些调整,并在下面给出了它。

document.querySelector("button[name='showAllBtn']").addEventListener("click",function(){
  var state = this.dataset.clicked;
  state = typeof state == "undefined" ? "Y" : state;
  ((state == "Y") ? showAllSteps : nextStep)();
  this.dataset.clicked = (state == "Y") ? "N" : "Y"; 
},false);

演示

function showAllSteps() {
    alert('showAllSteps');    
    expectedFunc = function() { nextStep(); };
}
function nextStep() {
    alert('nextStep');     
    expectedFunc = function() { showAllSteps(); };
}
function toggleFunction() {
    expectedFunc();
}
var expectedFunc = function() { showAllSteps(); };
<button type="button" class="btn" name="showAllBtn" onclick="toggleFunction()">Show all</button>

JsFiddle在这里(针对IE更新(:https://jsfiddle.net/t0g6ayhq/2/