在2个功能之间切换 [英] Toggle Between 2 Functions

查看:121
本文介绍了在2个功能之间切换的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图做一个切换功能,所以当你点击一个链接,它做一件事,当你再次点击相同的链接做另一件事。我遇到的问题是,我使用的是最新版本的Jquery,似乎toggle-event是弃用

I'm trying to make a toggle function, so when you click a link it does one thing and when you click the same link again it does another thing. My problem comes is that I'm using the latest version of Jquery and it seems that toggle-event is Deprecated.

我在尝试使用这个之前,我发现它已被弃用。

I was trying to work with this before I found it was deprecated.

$('#edit a').toggle(
     function(){
        editList();
    },
     function(){
        addList();
});

它在文档中说它已经绑定为单击。

It says in the docs that it's already binded to click.

推荐答案

微型jQuery插件:

A micro jQuery plugin:

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

取自我的回答这里 http://stackoverflow.com/a/21520499/383904

还有其他方法可以切换状态/值:

There's other ways to toggle a state / value:

LIVE DEMO

LIVE DEMO

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运算符 ^ like: [c ^ = 1] code>

where instead of the modulo operator % you can use the
Bitwise XOR operator ^ like: [c^=1]

使用Array.reverse()

LIVE DEMO

Using Array.reverse()
LIVE DEMO

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]()

reverse will invert our array on every click, all we need to do is take the 0 indexed value [0] and run that function name [0]().

这篇关于在2个功能之间切换的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆