Jquery-相同的对象,多次单击,多个功能

时间:2012-07-25 05:00:33

标签: jquery function click

我试图找出实现单击object1一次并导致一次函数(动画对象A),然后再次单击object1并导致另一个函数(动画另一个对象-B)的效果的最佳方法,等。

有人可以折腾我的一些术语,在这里使用什么?我知道如何通过jQuery / CSS add / remove / toggle类来实现动画,但我正在寻找最有效的方法。

1 个答案:

答案 0 :(得分:1)

您正在寻找JQuery“一次性”事件处理程序。

http://api.jquery.com/one/

function first() {
    $('#a').animate();
};

function next() {
    $('#b').animate();
};

$('#button').one('click', function() {
    first();
    $('#button').click(next);
};

这会在第一次触发click事件时运行first函数,然后将click事件重新绑定到next函数以进行所有后续点击。

编辑:或者,如果您有两个并希望它们替代,您可以使用Vishal的toggle建议:http://api.jquery.com/toggle-event/

编辑2

另一种方法是在事件处理程序中保留一个计数器,如下所示:

function fireA() { /*...*/ }
function fireB() { /*...*/ }
function fireC() { /*...*/ }

$('#button').click(function() {
   var events = [fireA, fireB, fireC];

   //declare counter
   if(!this.counter) { this.counter = 0; }

   events[this.counter]();
   this.counter = (this.counter + 1) % 3;
});
相关问题