Toggling click handlers in Javascript

后端 未结 6 741
庸人自扰
庸人自扰 2021-01-05 14:54

I have an HTML button to which I attach an event, using jQuery\'s bind(), like so:

$(\'#mybutton\').bind(\'click\', myFirstHandlerFunction);
         


        
6条回答
  •  清酒与你
    2021-01-05 15:14

    This solution is a hack, but it is short and sweet for your rough work:

    $('#myButton').click(function() {
      (this.firstClk = !this.firstClk) ? firstHandler(): secondHandler();
    });
    

    It's a hack because it's putting a new property directly onto this which is the click-target HTML DOM element, and that's maybe not best practice. However, it thus avoids creates any new globals, and it can be used unchanged on different buttons simultaneously.

    Note that the first part of the ternary operation uses = and not == or ===, i.e. it's an assignment, not a comparison. Note also that the first time the button is clicked, this.firstClk is undefined but is immediately negated, making the first part of the ternary operation evaluate to true the first time.

    Here's a working version:

    $('#a > button').click(function() {(this.firstClk = !this.firstClk) ? a1(): a2();});
    $('#b > button').click(function() {(this.firstClk = !this.firstClk) ? b1(): b2();});
    
    function a1() {$('#a > p').text('one');}
    function a2() {$('#a > p').text('two');}
    
    function b1() {$('#b > p').text('ONE');}
    function b2() {$('#b > p').text('TWO');}
    div {display: inline-block;width: 10em;}
    
    

    not yet clicked

    NOT YET CLICKED

提交回复
热议问题