JSFiddle中的组复选框:第1部分 [英] Group checkboxes in JSFiddle : Part 1
问题描述
我正在尝试通过选择selectAll来进行组复选框.请检查JSFiddle以获得代码示例
I am trying to do group checkboxes by selecting selectAll. Please check JSFiddle for code sample
<fieldset>
<!-- these will be affected by check all -->
<div><input type="checkbox" ID="checkall1" onclick="CheckAllClick('checkall1');"> Check all</div>
<div><input type="checkbox"> Checkbox</div>
<div><input type="checkbox"> Checkbox</div>
<div><input type="checkbox"> Checkbox</div>
</fieldset>
<fieldset>
<!-- these won't be affected by check all; different field set -->
<div><input type="checkbox" ID="checkall2" onclick="CheckAllClick('checkall2');"> Check all</div>
<div><input type="checkbox"> Checkbox</div>
<div><input type="checkbox"> Checkbox</div>
<div><input type="checkbox"> Checkbox</div>
</fieldset>
function CheckAllClick(id){
alert(id);
$(id).closest('fieldset').find(':checkbox').prop('checked', this.checked);
}
推荐答案
您的函数存在一些问题:尝试这种方式:
You have some issues in your function: Try this way:
function CheckAllClick(elem) {
$(elem).closest('fieldset').find(':checkbox').prop('checked', elem.checked);
}
标记
<input type="checkbox" ID="checkall1" onclick="CheckAllClick(this);">Check all</div>
Fiddle
将onclick函数中的元素作为this
传递,并在您的代码中对其进行访问.
Pass the element in the onclick function as this
and access it in your code.
如果可以使用jquery方法,那么:
If you can go with jquery approach then:
将课程添加到您的所有复选框
Add a class to your checkall check boxes
<input type="checkbox" class="checkAll" ID="checkall1" >Check all
使用相同的代码,如果要单击标签以选中复选框,然后将其包装在label
标签中,则可以通过将所有复选框包装在标签中来对所有复选框进行相同的操作,这通常是一种标准方法:
With the same code, if you want to make the label click to check the checkbox then just wrap them in label
tag, same thing you can do with all the checkboxes by wrapping them in label which generally is a standard way:
<label><input type="checkbox" class="checkAll" ID="checkall1" >Check all<label>
将事件处理程序绑定到类
Bind an event handler to a class
$('.checkAll').on('change', function(){
$(this).closest('fieldset').find(':checkbox').prop('checked', this.checked);
})
Fiddle
这篇关于JSFiddle中的组复选框:第1部分的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!