I made a bootstrap form and am using jquery to handle all the clicks in the form.
我做了一个bootstrap表单,并使用jquery来处理表单中的所有点击。
<form class="form">
<div id="one" class="btn-group input-group btn-group" data-toggle="buttons">
<label class="btn btn-primary btn-xs active">
<input id="a" type="radio" />Choice A</label>
<label class="btn btn-primary btn-xs ">
<input id="b" type="radio" />Choice B</label>
</div>
</form>
<script>
$("#one").on("change", function(e){
if (e.target.id=="a"){
console.log("a")
}else{
console.log("b")
}
});
</script>
The button group is a radio style, with only one button active. Goal is to only execute the callback function if a new button is clicked.
按钮组是一种无线电样式,只有一个按钮处于活动状态。目标是仅在单击新按钮时执行回调函数。
Choice A is active by default via the class active. I was expecting that clicking this button would not fire an event since nothing is changed. But the callback function in the jquery does get executed when clicking Choice A for the first time after the page has loaded. After you clicked a button once, it behaves as expected, only logging a or b if it is not active.
默认情况下,选项A在活动类中处于活动状态。我原以为单击此按钮不会触发事件,因为没有任何更改。但是,在页面加载后第一次单击“选择A”时,jquery中的回调函数会执行。单击一次按钮后,它会按预期运行,仅记录a或b(如果它不活动)。
Is there a way to setup the html so that clicking the "active" choice does not trigger the jquery on change?
有没有办法设置html,以便单击“活动”选项不会触发更改jquery?
1 个解决方案
#1
$("#one input").on("change", function(e){
if ($(this).attr('id')=="a"){
console.log("a")
}else{
console.log("b")
}
});
and you can add class for label using
并且您可以使用添加标签类
$('#one label').removeClass('active');
$(this).closest('label').addClass('active');
#1
$("#one input").on("change", function(e){
if ($(this).attr('id')=="a"){
console.log("a")
}else{
console.log("b")
}
});
and you can add class for label using
并且您可以使用添加标签类
$('#one label').removeClass('active');
$(this).closest('label').addClass('active');