在两个功能之间切换

Toggle Between 2 Functions

本文关键字:功能 之间 两个      更新时间:2023-09-26

我想做一个切换功能,所以当你点击一个链接,它做一件事,当你再次点击相同的链接,它做另一件事。我的问题是,我使用的是最新版本的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;
});