我试图做一个切换功能,所以当你点击一个链接时,它会做一件事,当你再次点击相同的链接时,它会做另一件事。我的问题是,我使用的是最新版本的Jquery,看起来切换事件是Deprecated。在2个函数之间切换
我在尝试使用它之前,我发现它已被弃用。
$('#edit a').toggle(
function(){
editList();
},
function(){
addList();
});
它在文档中说它已经被绑定点击。
我试图做一个切换功能,所以当你点击一个链接时,它会做一件事,当你再次点击相同的链接时,它会做另一件事。我的问题是,我使用的是最新版本的Jquery,看起来切换事件是Deprecated。在2个函数之间切换
我在尝试使用它之前,我发现它已被弃用。
$('#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
});
其中,代替模运算%
可以使用
位异或操作^
,如:[c^=1]
使用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]();
});
反向将在每次点击时反转我们的阵列,我们所需要做的就是取0索引值[0]
并运行该函数名称[0]()
。
我喜欢这种简单。 – 2013-03-24 20:22:19
@Howdy_McGee不像我两年后的回答那么简单。结帐我的关闭。 – t3dodson 2015-05-22 07:43:23
不优雅,但快速修复:
$('#edit a').click({
if($(this).data('toggleState') == 1) {
toggleState = 0;
addList();
}
else {
toggleState = 1;
editList();
}
$(this).data('toggleState', toggleState);
return false;
});
从它的外观来看,没有解决方案会变得优雅。 – 2013-03-24 20:20:31
所有你需要做的是有一个变量,或属性,指示执行何种功能,例如,使用自定义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;
}
});
短和清洁
var toggle = [addList, editList];
$('#edit a').click({
var state = +$(this).data('toggle');
toggle[state]();
$(this).data('toggle',(1-state));
return false;
});
见我对这个here
该解决方案的答案创建构成每次调用时两者之间两个功能交替切换功能。
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();
}));
很酷。另请参阅使用'.clickToggle()'微型jQuery插件这个不错的方法:http://stackoverflow.com/a/21520499/383904或者更好的方法 – 2015-05-22 09:23:21
@ RokoC.Buljan这真的很类似。我更喜欢这种方式,因为它不会在运行时更改任何对象。并没有jQuery的依赖。 – t3dodson 2015-05-22 18:11:55
应用它我不知道这个问题是在这里。你在问怎么做? HTTP://forum.jquery。com/topic/beginner-function-toggle-deprecated-what-to-use-instead简单的搜索。 – 2013-03-24 20:13:37