如何在功能之间切换?

时间:2016-05-14 16:16:59

标签: javascript toggle togglebutton

HTML

<button type="button" class="btn" name="showAllBtn" onClick="showAllSteps()">Show all</button>

JS

function showAllSteps()
{
//code  
}
function nextStep()

{
//code
}

如果我点击显示全部按钮,它应该在这两个功能之间切换。任何人都可以帮助我吗?

2 个答案:

答案 0 :(得分:1)

您可以使用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);

DEMO

答案 1 :(得分:1)

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/