在两个功能之间切换
Toggle Between 2 Functions
我想做一个切换功能,所以当你点击一个链接,它做一件事,当你再次点击相同的链接,它做另一件事。我的问题是,我使用的是最新版本的Jquery,似乎toggle-event已弃用。
在我发现它被弃用之前,我试图使用它。
$('#edit a').toggle(
function(){
editList();
},
function(){
addList();
});
在文档中说它已经被绑定到click
一个微型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
});
可以用
代替模算子%
位异或运算符 ^
like: [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;
});
看我的回答在这里
此解决方案创建了一个toggle函数,该函数由两个函数组成,每次调用时在两者之间交替。
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();
}));
不优雅,但快速修复:
$('#edit a').click({
if($(this).data('toggleState') == 1) {
toggleState = 0;
addList();
}
else {
toggleState = 1;
editList();
}
$(this).data('toggleState', toggleState);
return false;
});
相关文章:
- 在周一上午8点至晚上7点之间执行功能
- 在两种功能之间进行选择的建议
- AngularJS控制器之间共享代码/方法/功能
- 如何在Angular JS中的控制器之间共享搜索功能
- 这两个 Angular 控制器之间的功能有什么区别吗?
- 在控制器 AngularJS 之间共享功能
- 在多个 angularjs 项目之间共享通用功能/配置
- 在不同的视图之间共享相同的操作/功能
- 在 2 个不同的功能之间共享 $scope.数据
- 这两个功能之间有什么区别?(JavaScript)
- 获取两个位置之间的距离和时间的功能
- ES7异步功能和promise之间的技术差异
- 定时功能和用户启动功能之间的冲突
- 在两种颜色之间切换的功能
- 这些功能之间的差异
- 向Javascript原型添加方法和向现有对象添加功能之间的区别是什么?
- 具有动画的功能之间的延迟/排队
- 在两个功能之间切换
- 如何在按钮点击功能之间切换
- 功能之间的空格和括号在VS JS编辑器