我有这个jQuery的:
$(document).ready(function() {
$('#masterChecks input[type="checkbox"]').click(function() {
var togClass=$(this).attr('class');
if($(this).attr('checked')){
//need to make sure all checkboxes for this class is checked, when the
//master checkbox is checked.
$('div.' + togClass ).css("display", "inline-block");
}
else
{
//need to make sure all checkboxes for this class is unchecked, when the
//master checkbox is checked.
$('div.' + togClass ).css("display", "none");
}
});
});
我有很多div和很多类的HTML。有很多复选框。现在,我正在检查mastercheckbox,它将隐藏与该复选框具有相同类的所有属性的css。我也有一组本地复选框,它们的功能相同,但仅适用于它们所在的div。我希望Jquery在未选中时取消选中具有相同类的本地checbox,反之亦然。这是HTML结构
<div id="masterChecks">
// checbox here with class="sampleclass"
</div>
<div class="sampleclass">
//local checkbox here
</div>
看起来很简单,但无法正常工作,
香港专业教育学院尝试过这样的事情:
$('div.' + togClass + 'input[type="checkbox"]').attr('checked','checked');
有人可以帮忙吗?
最佳答案
您可以使用jquery函数.is()来检查复选框的状态,然后使用.each()函数来提示并将所有具有相同类的复选框的状态设置为主菜单之一:
$('#masterChecks input[type="checkbox"]').click(function(){
var checkclass= $(this).attr('class');
if($(this).is(':checked'))
$('div.' + checkclass + ' input[type="checkbox"]').each(function(){
$(this).attr('checked', true);
});
else
$('div.' + checkclass + ' input[type="checkbox"]').each(function(){
$(this).attr('checked', false);
});
});
编辑:
添加了jsfiddle的工作代码:http://jsfiddle.net/CFeam/2/