jQuery简化函数有几个复选框
我有几个复选框,我想简化下一个函数 我不想每次都重复相同的代码。我想使用数据属性jQuery简化函数有几个复选框,jquery,Jquery,我有几个复选框,我想简化下一个函数 我不想每次都重复相同的代码。我想使用数据属性 <input id="homeView" class="home-checkbox" type="checkbox" /> <input id="homeAll" class="home-checkbox" type="checkbox" /> $('#homeAll').on('click',function() { if(this.chec
<input id="homeView" class="home-checkbox" type="checkbox" />
<input id="homeAll" class="home-checkbox" type="checkbox" />
$('#homeAll').on('click',function()
{
if(this.checked)
{
$('.home-checkbox').each
(
function()
{
this.checked = true;
}
);
}
else
{
$('.home-checkbox').each
(
function()
{
this.checked = false;
}
);
}
});
谢谢简化版:
$('#homeAll').on('click',function() {
if(this.checked)
$('.home-checkbox').prop("checked", true);
else
$('.home-checkbox').prop("checked", false);
});
演示:这是一个简单的!看:
$'homeAll'。单击,函数{
$'.home checkbox'.propchecked,this.checked;
};
$'pagesAll'。单击,函数{
$'.pages复选框'.propchecked,this.checked;
};
一个家
全在家
一页
所有页面试试这个。我使用了一种添加名为“data attr”的属性的方法。有了它,您所要做的就是添加数据attr='classname',它将适用于所有复选框集
<input id="homeView" class="home-checkbox" data-attr="home-checkbox" type="checkbox" />homeView
<input id="homeAll" class="home-checkbox all" type="checkbox" />homeAll
<input id="pagesView" class="pages-checkbox" data-attr="pages-checkbox" type="checkbox" />pagesView
<input id="pagesAll" class="pages-checkbox all" type="checkbox" />pagesAll
$('.all').on('click',function()
{
var $this = $(this);
var isChecked = this.checked;
$('input').each(function()
{
if($this.hasClass($(this).attr("data-attr")))
if(isChecked)
$(this).prop("checked",true);
else
$(this).prop("checked",false);
});
});
在本演示中,对于控制其他复选框状态的复选框,只需将类全部放入。这段代码不必重复——它以类all的每个元素为目标 $document.readyfunction{ $'.all'。关于“更改”,函数{ var allCheck=$this; var classes=$this.attr'class'; $'.+类。拆分“”[0]+。每个函数{ if allCheck.is':选中'{ $this.prop'checked',true; } 否则{ $this.prop'checked',false; } }; }; };
你能更具体地说明你想做什么吗?“下一个函数”是怎么回事?您应该在“框架和扩展”下选择jQuery的一个版本。如果不这样做,所有函数都无法工作。这有用吗@GrafiCodeStudio缺少一个功能,即如果两者都选中,则第一个复选框将自动取消选中第二个。@wrxsti我认为OP应该编辑他的问题,包括缺少的代码部分。您的代码只针对id=homeAll的复选框,这意味着对于另一组复选框,您需要为另一个id添加相同的逻辑。@Dinmyte yep,问题在此回答之后被编辑。您必须为我想要的每个varAll checkbox重复此代码。当我取消选中复选框时,checkbox all是取消选中的。
$('input:checkbox').on('click',function()
{
var $this = $(this);
var isChecked = this.checked;
var $thisClass = $(this).attr("class");
$('input').each(function()
{
if($this.hasClass($(this).attr("data-attr")))
{
if(isChecked)
$(this).prop("checked",true);
else
$(this).prop("checked",false);
}
else if($(this).hasClass($thisClass) && !isChecked)
{
if(isChecked)
$(this).prop("checked",true);
else
$(this).prop("checked",false);
}
});
});