[英]Uncheck the checkbox when no element is selected. check only one checkbox. change background-color of relevent div container.
<div id="grand-parent" class="grand-parent">
<div class="parent-div">
<p> A </p>
<input type="checkbox" class="select-me" name="1" value="1"/>
</div>
</div>
<div id="grand-parent-1" class="grand-parent">
<div class="parent-div">
<p> B </p>
<input type="checkbox" class="select-me" name="2" value="2"/>
</div>
</div
><div id="grand-parent-2" class="grand-parent">
<div class="parent-div">
<p> C </p>
<input type="checkbox" class="select-me" name="3" value="3"/>
</div>
</div>
$('.select-me').change(function(){
if($(this).is(':checked'))
{
$('.select-me').each(function(){ $(this).attr('checked', false); });
$(this).attr('checked', true);
$('#grand-parent').css('background','#999');
}
else if($(this).not(':checked')){
$('.select-me').each(function(){ $(this).attr('checked', false); });
$(this).attr('checked', false);
$('.grand-parent').css('background','green');
}
});
Jsfiddle http://jsfiddle.net/2XsY5/27/
我需要幫助來更改相關復選框的背景顏色。 一次只能選擇一個復選框。 所有未選中的復選框應具有默認的背景色。 只有所需的復選框應具有不同的背景色。 感謝您的幫助。
如果您一次只要檢查一個表單元素,我建議使用radio
元素。
要解決背景問題,您可以使用change事件將輸入元素設為父級:
$('[type=checkbox]').change(function(){
$('[type=checkbox]').not(this).removeAttr('checked').parents('.grand-parent').removeClass('selected');
$(this).parents('.grand-parent').addClass('selected');
});
注意:更新了演示,以根據要求將類添加到父級div,並將類刪除到所有未選中的輸入。
將DOM遍歷到所需元素的方法有很多,可以使用.parent().parent()
或其他方法,但結果是相同的。
您能嘗試一下嗎,希望這是您所期望的!
$(function(){
$('.select-me').change(function(){
$this = $(this);
$('.select-me').each(function(){
if($(this).val()==$this.val())
{
$(this).parents('.grand-parent').css('background','#999');
}else{
$(this).attr('checked', false);
$(this).parents('.grand-parent').css('background','green');
}
});
});
});
演示: http : //jsfiddle.net/FvN7v/
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.