提供按钮开/关功能

时间:2019-07-02 12:19:30

标签: javascript jquery html

我有5个按钮。每个按钮都链接到一个功能,该功能将在单击时显示一些数据。我正在研究一种功能,其中一旦单击按钮,它应该使用数据运行该函数;如果我再次单击同一按钮,则应该再次取消选择该按钮,并应该返回另一个函数,在该函数中我加载页面的默认数据(另一个功能)。我尝试使用以下代码,但无法正常工作,请帮助我获得正确的输出。

我正在遍历所有按钮以检查单击了哪个按钮,如果单击了该按钮,则向其添加类,但无法检查第二次单击。

$('.boxCount ').click(function(e){
  var btns = $('.boxCount ');
  for(var i = 0; i < btns.length; i++){
    var btnClicked = $(e.currentTarget);
    btnClicked.addClass('active');
  }
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button id="btn1" class="boxCount col-md-2" title="Moving Vehicle">Button 1</button>
<button id="btn2" class="boxCount col-md-2" title="Moving Vehicle">Button 2</button>
<button id="btn3" class="boxCount col-md-2" title="Moving Vehicle">Button 3</button>
<button id="btn4" class="boxCount col-md-2" title="Moving Vehicle">Button 4</button>
<button id="btn5" class="boxCount col-md-2" title="Moving Vehicle">Button 5</button>

我正在寻求实现按钮的按钮打开/关闭功能,以便我可以在第一次单击时运行一个功能(打开方法)并为第二次单击运行默认功能(另一个功能),这是一个(关闭)功能按钮。

2 个答案:

答案 0 :(得分:2)

您可以像下面这样简单地使用toggleClass()在单击的按钮上切换类:

$('.boxCount').click(function(e){
    $(this).toggleClass('active');
});
.active{
  background-color: green;
  color: white;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button id="btn1" class="boxCount col-md-2" title="Moving Vehicle">Button 1</button>
<button id="btn2" class="boxCount col-md-2" title="Moving Vehicle">Button 2</button>
<button id="btn3" class="boxCount col-md-2" title="Moving Vehicle">Button 3</button>
<button id="btn4" class="boxCount col-md-2" title="Moving Vehicle">Button 4</button>
<button id="btn5" class="boxCount col-md-2" title="Moving Vehicle">Button 5</button>

答案 1 :(得分:0)

要扩展Mamun的答案,通常当我遇到需要在按钮上打开/关闭功能的情况时,我会这样做:

    $('.boxCount').click(function(e){
        //add e.preventDefault() here if your button 
        //includes links that you don't want them to go anywhere
        if($(e.currentTarget).hasClass("active")) {
            $(e.currentTarget).removeClass("active")
            //functionality for when you need the button to stay 'off' and do other things in the meantime
        }
        else {
            $(e.currentTarget).addClass("active");
            //for when the button needs to stay on, doing other things in the meantime
        }
        //add return false; here if you have links 
        //that don't go anywhere (this is for older browsers)
    });

之所以这样,是因为通常在“打开”状态下我会执行一些操作,并且也会执行相同的操作,因此简单的toggleClass无效