jQuery click / toggle between two functions

前端 未结 10 1662
野的像风
野的像风 2020-11-22 07:58

I am looking for a way to have two separate operations / functions / \"blocks of code\" run when something is clicked and then a totally different block when the same thing

10条回答
  •  轮回少年
    2020-11-22 08:39

    Use a couple of functions and a boolean. Here's a pattern, not full code:

     var state = false,
         oddONes = function () {...},
         evenOnes = function() {...};
    
     $("#time").click(function(){
         if(!state){
            evenOnes();
         } else {
            oddOnes();
         }
         state = !state;
      });
    

    Or

      var cases[] = {
          function evenOnes(){...},  // these could even be anonymous functions
          function oddOnes(){...}    // function(){...}
      };
    
      var idx = 0; // should always be 0 or 1
    
      $("#time").click(function(idx){cases[idx = ((idx+1)%2)]()}); // corrected
    

    (Note the second is off the top of my head and I mix languages a lot, so the exact syntax isn't guaranteed. Should be close to real Javascript through.)

提交回复
热议问题