[英]jQuery Checkbox selection and change class
我有这样的形式:
<form action='' onsubmit='void(0)' class="mainform">
<label class="form3"><input type="checkbox"> One a fancy cross-browser styled checkbox</label>
<label class="form3"><input type="checkbox"> two a fancy cross-browser styled checkbox</label>
<label class="form3"><input type="checkbox"> Three a fancy cross-browser styled checkbox</label>
<label class="form3"><input type="checkbox"> Four a fancy cross-browser styled checkbox</label>
<label class="form3"><input type="checkbox"> Five a fancy cross-browser styled checkbox</label>
<label class="form3"><input type="checkbox"> Six a fancy cross-browser styled checkbox</label>
<label class="form3"><input type="checkbox"> Seven a fancy cross-browser styled checkbox</label>
<label class="form3"><input type="checkbox"> eight a fancy cross-browser styled checkbox</label>
<label class="form3"><input type="checkbox"> 9 a fancy cross-browser styled checkbox</label>
<label class="form3"><input type="checkbox"> 10 a fancy cross-browser styled checkbox</label>
<label class="form3"><input type="checkbox"> 11 a fancy cross-browser styled checkbox</label>
<label class="form3"><input type="checkbox"> 12 a fancy cross-browser styled checkbox</label>
<label class="form3"><input type="checkbox"> 13 a fancy cross-browser styled checkbox</label>
<label class="form3"><input type="checkbox"> 14 a fancy cross-browser styled checkbox</label>
</form>
现在,我要这样做。 当用户选中或取消选中复选框时,我想向标签添加/删除类,以便在选中和未选中复选框时可以显示不同颜色的文本。
我正在尝试做到这一点:
$(document).ready(function(){
$('.form3').each(function(i,e) {
if(checklist[i] == "")
{
$(this).find('input[type=checkbox]').attr('checked', false);
$(this).appendTo($('form'));
$(this).find('input[type=checkbox]').change(function() {
$(this).closest('label').addClass("checkselected");
});
$(this).closest('label').removeClass("checkselected");
}
else
{
$(this).find('input[type=checkbox]').attr('checked', true);
$(this).find('input[type=checkbox]').change(function() {
$(this).closest('label').removeClass("checkselected");
});
$(this).closest('label').addClass("checkselected");
}
});
});
现在我知道这可能不是正确的方法,因为我正在“ $('。form3')。each(function(i,e)”
这使它可以工作,但是只有一次。 即使多次单击同一复选框,如何使它正常工作。
如果我正确理解了您的问题,那么您要做的就是将click事件处理程序绑定到所有复选框,然后将一个类添加/删除到被单击对象的父label
中。 如果正确,则可以执行以下操作:
$("input[type='checkbox']").change(function() {
$(this).closest("label").toggleClass("someClass");
});
toggleClass
方法使您无需检查是否已选中复选框。 您可以传递第二个参数来显示是否应该添加或删除该类,因此,如果某些复选框开始时已被选中,则可能需要使用该参数:
$("input[type='checkbox']").change(function() {
$(this).closest("label").toggleClass("someClass", this.checked);
});
这是上述代码的有效示例 。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.