简体   繁体   English

如何使用jQuery切换JavaScript功能

[英]How to toggle javascript functions using jquery

I have two javascript functions 我有两个JavaScript函数

 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: 为了完整起见,下面是一个使用data属性的示例:

$("#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. 您可以使用布尔变量(true)并在调用第一个函数后将其设置为false。 Then if false call the second one and set the boolean variable again (to true). 然后,如果为false,则调用第二个变量,并再次设置布尔变量(为true)。

Use .data() to set a variable on the element itself, which tells you which function to call. 使用.data()在元素本身上设置一个变量,该变量告诉您​​要调用的函数。

 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();
    }
 });

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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