关于在jQuery

时间:2015-09-02 07:31:08

标签: javascript jquery

请你看一下这个演示,让我知道如何在toggle()之外调用/切换两个函数

function printConsole() {
  console.log("This is From Function A");
}

function printAlert() {
  alert("This is From Function B");
}

$("#toggler").toggle(
  printConsole(); printAlert();
);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.2/jquery.min.js"></script>
<button id="toggler">Toggle Fnctions</button>

2 个答案:

答案 0 :(得分:1)

尝试使用.click()Array.prototype.reverse()

将函数存储在数组中

function printConsole() {
  console.log("This is From Function A");
}

function printAlert() {
  alert("This is From Function B");
}

var fns = [printConsole, printAlert];

$("#toggler").click(function() {
  fns[0]();
  fns.reverse();
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.2/jquery.min.js"></script>
<button id="toggler">Toggle Fnctions</button>

答案 1 :(得分:0)

在jquery 1.8中贬值

使用逗号,试试这段代码:

$("#toggler").toggle(
  function() {
  console.log("This is From Function A");
},function() {
  alert("This is From Function B");
}
);

参考:https://api.jquery.com/toggle-event/

<强>更新

使用此代替:

var clicks = true;
$('a').click(function() {
  if (clicks) {
    alert('Function A');
    clicks = false;
  } else {
    alert('Function B');
    clicks = true;
  }
});

参考:Alternative to jQuery's .toggle() method that supports eventData?