jQuery click / toggle between two functions

前端 未结 10 1661
野的像风
野的像风 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:29

    I don't think you should implement the toggle method since there is a reason why it was removed from jQuery 1.9.

    Consider using toggleClass instead that is fully supported by jQuery:

    function a(){...}
    function b(){...}   
    

    Let's say for example that your event trigger is onclick, so:

    First option:

    $('#test').on('click', function (event) {
    
        $(this).toggleClass('toggled');
    
        if ($(this).hasClass('toggled')) {
            a();
        } else{
            b();
        }
    }
    

    You can also send the handler functions as parameters:

    Second option:

    $('#test').on('click',{handler1: a, handler2: b}, function (event) {
    
        $(this).toggleClass('toggled');
    
        if ($(this).hasClass('toggled')) {
            event.data.handler1();
        } else{
            event.data.handler2();
        }
    }
    

提交回复
热议问题