在两个功能之间切换

时间:2013-03-24 20:06:48

标签: javascript jquery click toggle

我正在尝试进行切换功能,因此当您点击链接时它会做一件事,当您再次点击相同的链接时,它会做另一件事。我的问题是我使用的是最新版本的Jquery,似乎toggle-event是Deprecated

在我发现它被弃用之前,我试图使用它。

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

它在文档中说它已经绑定了点击。

5 个答案:

答案 0 :(得分:4)

您需要做的就是拥有一个变量或属性来指示要运行的功能,例如,使用自定义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 Fiddle demo

答案 1 :(得分:3)

微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


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

<强> 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运算符 ^,如:[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]();
});

reverse将在每次单击时反转我们的数组,我们需要做的就是取0索引值[0]并运行该函数名[0]()

答案 2 :(得分:2)

简短而干净

var toggle = [addList, editList];
$('#edit a').click({
  var state = +$(this).data('toggle');
  toggle[state]();
  $(this).data('toggle',(1-state));
  return false;
});

答案 3 :(得分:1)

不优雅,但快速修复:

$('#edit a').click({
  if($(this).data('toggleState') == 1) {
    toggleState = 0;
    addList();
  }
  else {
    toggleState = 1;
    editList();
  }

  $(this).data('toggleState', toggleState);
  return false;
});

答案 4 :(得分:1)

请参阅我对此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();
}));