如何在一个按钮上运行多个动作

时间:2018-06-18 04:54:55

标签: javascript jquery

我有一个提交按钮,现在我想要这样的结果:

当我第一次点击它时,它将运行动作1。

当我第二次点击时,它将运行动作2。

当我点击n时,它将运行动作n。

我该怎么做?

1 个答案:

答案 0 :(得分:6)

以下是我找到Here的工作解决方案。

$.fn.toggleClick = function(funcArray) {
  return this.click(function() {
    var elem = $(this);
    var index = elem.data('index') || 0;

    funcArray[index]();
    elem.data('index', (index + 1) % funcArray.length);
  });
};

$('.btn').toggleClick([
  function() {
    alert('From Function 1');
  }, function() {
    alert('From Function 2');
  }, function() {
    alert('From Function 3');
  }, function() {
    alert('From Function 4');
  }
]);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<button type="button" class="btn">Click Me</button>

这可能会对你有帮助。

问候。