我有一個有多個複選框組的jQuery腳本。如果選擇了「家長」,則還應選擇所有「孩子」框,並且如果有任何「孩子」框未被選中,則「家長」也應該被取消選擇,並且只有選中的「孩子」框被選中。jquery複選框組檢查/取消選中只能工作一次
這裏是一個的jsfiddle:http://jsfiddle.net/9NmE7/
的問題是,與jQuery 1.4.2這個曾經工作的偉大,但由於升級到1.10.2它仍然有效,但只有一次。意思是,如果你點擊'家長1',它就可以工作。然後,您取消選擇「家長1」並且它也可以工作,但是如果您再次點擊「家長1」再次選擇它,則不再有效。
這裏有什麼問題?
以防萬一,這裏是HTML:
<form>
<fieldset>
<input type="checkbox" class="parentCheckBox" /> Parent 1<br />
<input type="checkbox" class="childCheckBox" /> Child 1-1<br />
<input type="checkbox" class="childCheckBox" /> Child 1-2<br />
<input type="checkbox" class="childCheckBox" /> Child 1-3<br />
<input type="checkbox" class="childCheckBox" /> Child 1-4<br />
<input type="checkbox" class="childCheckBox" /> Child 1-5<br />
</fieldset>
<fieldset>
<input type="checkbox" class="parentCheckBox" /> Parent 2<br />
<input type="checkbox" class="childCheckBox" /> Child 2-1<br />
<input type="checkbox" class="childCheckBox" /> Child 2-2<br />
<input type="checkbox" class="childCheckBox" /> Child 2-3<br />
<input type="checkbox" class="childCheckBox" /> Child 2-4<br />
<input type="checkbox" class="childCheckBox" /> Child 2-5<br />
</fieldset>
<fieldset>
<input type="checkbox" class="parentCheckBox" /> Parent 3<br />
<input type="checkbox" class="childCheckBox" /> Child 3-1<br />
<input type="checkbox" class="childCheckBox" /> Child 3-2<br />
<input type="checkbox" class="childCheckBox" /> Child 3-3<br />
<input type="checkbox" class="childCheckBox" /> Child 3-4<br />
<input type="checkbox" class="childCheckBox" /> Child 3-5<br />
</fieldset>
</form>
而jQuery的:
$(document).ready(
function() {
//clicking the parent checkbox should check or uncheck all child checkboxes
$(".parentCheckBox").click(
function() {
$(this).parents('fieldset:eq(0)').find('.childCheckBox').attr('checked', this.checked);
}
);
//clicking the last unchecked or checked checkbox should check or uncheck the parent checkbox
$('.childCheckBox').click(
function() {
if ($(this).parents('fieldset:eq(0)').find('.parentCheckBox').attr('checked') == true && this.checked == false)
$(this).parents('fieldset:eq(0)').find('.parentCheckBox').attr('checked', false);
if (this.checked == true) {
var flag = true;
$(this).parents('fieldset:eq(0)').find('.childCheckBox').each(
function() {
if (this.checked == false)
flag = false;
}
);
$(this).parents('fieldset:eq(0)').find('.parentCheckBox').attr('checked', flag);
}
}
);
}
);
很好用,謝謝:) – user2643870