Click toggle with jquery/javascript

前端 未结 5 2057
粉色の甜心
粉色の甜心 2021-01-07 13:17

I want to click a table element and to have it do x the first click and if clicked again perform Y

         


        
5条回答
  •  栀梦
    栀梦 (楼主)
    2021-01-07 13:31

    I'm going to assume (you didn't say) that you want the function to be called to alternate with every click:

    $('#e1').on('click', function() {
    
        // retrieve current state, initially undefined
        var state = $(this).data('state');  
    
        // toggle the state - first click will make this "true"
        state = !state; 
    
        // do your stuff
        if (state) {
            // do this (1st click, 3rd click, etc)
        } else {
            // do that
        }
    
        // put the state back
        $(this).data('state', state);  
    });
    

    This uses jQuery's .data feature to store the button's click state in the button element itself.

    Alternatively, you could use an external variable, but you should enclose the callback in a closure (in this case an immediately invoked function expression) to prevent the variable from becoming a global variable:

    (function() {
        var state;
    
        $('#e1').on('click', function() {
            state = !state; 
            if (state) {
                // do this (1st click, 3rd click, etc)
            } else {
                // do that
            }
        });
    })();
    

    If the .on call and the state variable declaration are inside a jQuery document.ready handler that would have the same effect.

提交回复
热议问题