我有一个分区和细分列表,我用复选框显示,通过数据库动态创建,最终结果有点像这样:
<input name="divisions[]" type="checkbox" value "division1"/> Division One <input name="departments[]" type="checkbox" value "department1"/> Department One <input name="departments[]" type="checkbox" value "department2"/> Department Two <input name="divisions[]" type="checkbox" value "division2"/> Division Two <input name="departments[]" type="checkbox" value "department3"/> Department Three <input name="departments[]" type="checkbox" value "department4"/> Department Four
我需要编写jQuery代码,例如当用户点击其所有部门的部门时,只有其部门被同等地点击或关闭。
我正在考虑将所点击的事件功能附加到打开或关闭所有直接部门的所有部门,但我不知道语法: 从概念上讲,我在想:
jQuery(document).ready(function() {
$(all_elements_with_the_name_divisions).click(function() {
$(all_immediately_following_elements_with_the_name_departments).attr('checked',this.checked);
});
})
感谢
答案 0 :(得分:3)
这样的事情应该可以解决问题。
<input type="checkbox" class="divisions" value="division1" />
<input type="checkbox" class="division1_departments" value="division1_departmen1" />
<input type="checkbox" class="division1_departments" value="division1_departmen2" />
<input type="checkbox" class="divisions" value="division2" />
<input type="checkbox" class="division2_departments" value="division2_departmen1" />
<input type="checkbox" class="division2_departments" value="division2_departmen2" />
<script type="text/javascript">
$(document).ready(function () {
$("input.divisions:checkbox").click(function () {
$("input." + $(this).val() + "_departments:checkbox").attr("checked", $(this).is(':checked'));
});
});
</script>
答案 1 :(得分:1)
如果您在<div>
中围绕每个群组,则可以使用siblings()
<div>
<input name="divisions[]" type="checkbox" value "division1"/> Division One
<input name="departments[]" type="checkbox" value "department1"/> Department One
<input name="departments[]" type="checkbox" value "department2"/> Department Two
</div>
<div>
<input name="divisions[]" type="checkbox" value "division2"/> Division Two
<input name="departments[]" type="checkbox" value "department3"/> Department Three
<input name="departments[]" type="checkbox" value "department4"/> Department Four
</div>
jQuery(document).ready(function() {
$('input[name="divisions\\[\\]"]').click(function() {
$(this).siblings('input[type="checkbox"]').attr('checked',this.checked);
});
})
答案 2 :(得分:1)
如果你能够像这样构建你的标记:
<div class="division">
<input name="divisions[]" type="checkbox" value "division1"/> Division One
<div class="department">
<input name="departments[]" type="checkbox" value "department1"/> Department One
<input name="departments[]" type="checkbox" value "department2"/> Department Two
</div>
</div>
以下代码应该执行您想要的操作:
$('.division input[name="divisions\\[\\]"]').click(function() {
$(this).find('.department input[type="checkbox"]').attr('checked', this.checked);
});