简体   繁体   中英

How to toggle javascript functions using jquery

I have two javascript functions

 function A(){ 
   alert("A() function is called");
 }

function B(){
    alert("B() function is called");
 }

 $("#button").click(function(){
 // I need to toggle A() and B() here
 });

How can I achieve this, can any one please help on this?

To achieve this you could store a flag which stores the state of the element, and therefore which function to call. Here's an example which uses a class:

$("#button").click(function(){
    var $el = $(this).toggleClass('foo');
    $el.hasClass('foo') ? A() : B();
});

You could bind/unbind event handlers on each successive click, but this quickly becomes unwieldy and a pain to maintain.

For the sake of completeness, here's an example that uses a data attribute instead:

$("#button").click(function(){
    var $el = $(this).data('foo', !$(this).data('foo'));
    $el.data('foo') ? A() : B();
});

you could change the binding

function A(){ 
   alert("A() function is called");
   $("#button").off("click", A).on("click", B);
 }

function B(){
   alert("A() function is called");
   $("#button").off("click", B).on("click", A);
 }

 $("#button").on("click", A);

You could use a boolean variable (true) and set it to false after calling the first fonction. Then if false call the second one and set the boolean variable again (to true).

Use .data() to set a variable on the element itself, which tells you which function to call.

 function A() { alert("A() function is called"); } function B() { alert("B() function is called"); } $("#button").click(function() { if ($(this).data('AorB') == 'B') { B(); $(this).data('AorB', 'A'); } else { A(); $(this).data('AorB', 'B'); }; }); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <button id="button">click me</button> 

you can do by applying class to the button and write depends on class

Live Demo

 <input type="button" class="callA" value="click me" id="button" />

 $("#button").click(function(){

   if($(this).hasClass('callA')){
           A();
    }
   else
    {
          B();
    }
 });

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM