jQuery click / toggle between two functions

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

    one line solution: basic idea:

    $('sth').click(function () {
        let COND = $(this).propery == 'cond1' ? 'cond2' : 'cond1';
        doSomeThing(COND);
    })
    

    examples on jsfiddle

    example 1, changing innerHTML of an element in a toggle-mode:

    $('#clickTest1').click(function () {
        $(this).html($(this).html() == 'click Me' ? 'clicked' : 'click Me');
    });
    

    example 2, toggling displays between "none" and "inline-block":

    $('#clickTest2, #clickTest2 > span').click(function () {
        $(this).children().css('display', $(this).children().css('display') == 'inline-block' ? 'none' : 'inline-block');
    });
    

提交回复
热议问题