Registering jQuery click, first and second click

前端 未结 9 883
佛祖请我去吃肉
佛祖请我去吃肉 2020-11-29 23:23

Is there a way to run two functions similar to this:

$(\'.myClass\').click(
    function() {
        // First click
    },
    function() {
        // Second         


        
9条回答
  •  悲&欢浪女
    2020-11-30 00:01

    In the method mentioned below We are passing an array of functions to our custom .toggleClick() function. And We are using data-* attribute of HTML5 to store index of the function that will be executed in next iteration of click event handling process. This value, stored in data-index property, is updated in each iteration so that we can track the index of function to be executed in next iteration.

    All of these functions will be executed one by one in each iteration of click event. For example in first iteration function at index[0] will be executed, in 2nd iteration function stored at index[1] will be executed and so on.

    You can pass only 2 functions to this array in your case. But this method is not limited to only 2 functions. You can pass 3, 4, 5 or more functions in this array and they will be executed without making any changes in code.

    Example in the snippet below is handling four functions. You can pass functions according to your own needs.

    $.fn.toggleClick = function(funcArray) {
      return this.click(function() {
        var elem = $(this);
        var index = elem.data('index') || 0;
    
        funcArray[index]();
        elem.data('index', (index + 1) % funcArray.length);
      });
    };
    
    $('.btn').toggleClick([
      function() {
        alert('From Function 1');
      }, function() {
        alert('From Function 2');
      }, function() {
        alert('From Function 3');
      }, function() {
        alert('From Function 4');
      }
    ]);
    
    
    

提交回复
热议问题