![](/img/trans.png)
[英]Add class to parent div when radio button is checked and remove class if other radio is checked
[英]Radio - add class at div when checked
如何將JS中的添加類添加到DIV或表格,當檢查無線電輸入時?
當我檢查一個 radio input 時,我想將 class table-selected添加到div class="table-item" 。
$(".table-item input").change(function() { var div = $(this).closest('.table-item'); $(this).is(":checked") ? div.addClass("table-selected") : div.removeClass("table-selected"); });
#test .table-item { border: solid 1px #666; height: 25px; background-color: #CCC } #test .table-selected { border: 1 px solid #F00; background-color: #00F }
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <div id="test"> <div class="table-item"> <div><label for="check1"><input type='radio' name='rad' value='1'>1</label></div> </div> <div class="table-item"> <div><label for="check2"><input type='radio' name='rad' value='2'>2</label></div> </div> <div class="table-item"> <div><label for="check3"><input type='radio' name='rad' value='3'>3</label></div> </div> </div>
但這工作有些錯誤,添加類,但未選中時不會將其刪除
您只是從選定的div
刪除該類。 永遠不會滿足三元條件的else
部分,因為那里的div
代表您選擇的按鈕。
您需要從所有 div 中刪除該類。
$(".table-item").removeClass('table-selected');
var div = $(this).closest('.table-item');
if ($(this).is(":checked")) {
div.addClass("table-selected");
}
在這里查看: https : //jsfiddle.net/g5o2w47v/
在添加到當前類之前,您必須從其他類中刪除類。 觸發器僅針對該元素觸發,因此檢查將針對該元素而非其他元素運行。 更新鏈接: https : //jsfiddle.net/m637ndrx/2/
$(".table-item input").change(function() {
var div = $(this).closest('.table-item');
$('.table-item').removeClass("table-selected")
$(this).is(":checked") ? div.addClass("table-selected") : div.removeClass("table-selected");
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.