在2个函数之间切换
我正在尝试进行切换function,因此当您单击链接时它会执行一项操作,当您再次单击相同的链接时,它会执行另一项操作。 我的问题是我正在使用最新版本的Jquery,似乎toggle-event是Deprecated 。
在我发现它被弃用之前,我试图使用它。
$('#edit a').toggle( function(){ editList(); }, function(){ addList(); });
它在文档中说它已经绑定了点击。
一个微jQuery插件:
jQuery.fn.clickToggle = function(a,b) { var ab = [b,a]; return this.on("click", function(){ ab[this._tog^=1].call(this); }); }; // USE LIKE: $("button").clickToggle(function() { console.log("AAA"); }, function() { console.log("BBB"); }); // Chain here other jQuery methods to your selector
取自我的回答https://stackoverflow.com/a/21520499/383904
还有其他方法可以切换状态/值:
现场演示
var editAdd = [editList, addList], // store your function names into array c = 0; // toggle counter function editList(){ // define function alert('EDIT'); } function addList(){ // define function alert('ADD'); } $('#edit a').click(function(e){ e.preventDefault(); editAdd[c++%2](); // toggle array index and use as function // % = Modulo operator });
而不是模数运算符%
你可以使用
按位XOR运算符 ^
如: [c^=1]
使用Array.reverse()
现场演示
var editAdd = [editList, addList]; function editList(){ alert('EDIT'); } function addList(){ alert('ADD'); } $('#edit a').click(function(e){ e.preventDefault(); editAdd.reverse()[0](); });
reverse会在每次单击时反转我们的数组,我们需要做的就是取0索引值[0]
并运行该函数名[0]()
。
您需要做的就是有一个变量或属性来指示要运行的函数,例如,使用自定义data-switch
属性:
$('a').click(function(e){ e.preventDefault(); var that = $(this); switch (that.data('switch')){ case 'a': // do something in situation 'a' console.log('Function one'); that.data('switch','b'); break; case 'b': // do something in situation 'b' console.log('Function two'); that.data('switch','a'); break; } });
JS小提琴演示 。
简短而干净
var toggle = [addList, editList]; $('#edit a').click({ var state = +$(this).data('toggle'); toggle[state](); $(this).data('toggle',(1-state)); return false; });
不优雅,但快速修复:
$('#edit a').click({ if($(this).data('toggleState') == 1) { toggleState = 0; addList(); } else { toggleState = 1; editList(); } $(this).data('toggleState', toggleState); return false; });
在这里看到我的答案
该解决方案创建了一个切换function,该function组成了两个函数,每次调用它们时都会在两个函数之间交替。
var toggle = function (a, b) { var togg = false; return function () { // passes return value back to caller return (togg = !togg) ? a() : b(); }; };
适用于
$('#btn').on('click', toggle (function (){ return editList(); }, function (){ return addList(); }));