我有5个按钮。每个按钮都链接到一个函数,该函数将显示一些单击时的数据。我正在研究一个功能,其中一旦单击按钮,它应该使用Data&再次,如果我第二次单击同一按钮,则应取消选择按钮,并应返回另一个功能,其中我加载页面的默认数据(另一个函数(。我尝试了以下代码&它不起作用,请帮助我获得适当的输出。
我正在循环浏览所有按钮以检查哪个按钮,如果单击了,我正在向其中添加类,但是我无法检查第二次单击。
$('.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>
我正在寻求实现按钮的按钮打开/关闭功能,以便我可以在第一次单击(打开方法(时运行一个函数,并运行默认函数(另一个函数(,以获得第二个单击&amp;这是一个(关闭(按钮。
您可以使用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>
扩展了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)
});
我这样做是因为通常在" on"上,我在那里发生了一些事情,所以一个简单的 toggleClass
无法正常工作