Use the answer that got best answer, as it is, well, the best.
Every element in jQuery has an unlimited number of data values associated with it. I used
data('iteration'). Because it probably has no value to begin with I refer to it using
$(this).data('iteration')||0
Which gives me zero to start off or whatever iteration we are up to,
- functions[iteration].apply(this,arguments)
calls one of the functions passed as arguments depending on the iteration count, first it's functions[0], then [1]…
- iteration= (iteration+1) %functions.length
Add 1 with the modulo operator( % ) to wrap around back to zero when I hit the end.
- $(this).data('iteration',iteration)
Store iteration back for the next time around (the next time it is clicked)
It all comes naturally to me, but it is packed with a few complex tricks.
- $.fn.toggleClick=function(){
- var functions=arguments
- return this.click(function(){
- var iteration=$(this).data('iteration')||0
- functions[iteration].apply(this,arguments)
- iteration= (iteration+1) %functions.length
- $(this).data('iteration',iteration)
- })
- }
- $(function(){
- $('#mydiv').toggleClick(function(){ alert("odd")},function(){alert("even")})
- })
JΛ̊KE