我有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>
我希望实现按钮的按钮开/关功能,这样我就可以在第一次单击(开关方法)时运行一个功能,并在第二次单击时运行默认功能(另一个功能)&这是一个(关闭)按钮。
发布于 2019-07-02 12:48:02
为了扩展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
是不能工作的
发布于 2019-07-02 12:26:07
您可以使用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>
https://stackoverflow.com/questions/56852322
复制