2011-10-06 55 views
2

我有一个这样的形式:jQuery的复选框的选择和变化类

<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> 

现在,我想这样做。 当用户选中或取消选中某个复选框时,我想向标签中添加/删除类,以便在选中复选框时以及不选中时显示不同的彩色文本。

我试图做到这一点liek这样的:(”。form3' )。

$(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"); 
    } 
}); 
}); 

现在我知道,这maynot是这样做,因为我在里面的“$这样做的正确的方式各(函数(I,E)”

这使得它的工作,但只有一次。 我怎样才能使其与mulltiple点击相同的复选框,甚至工作。

回答

4

如果我理解正确你的问题,然后你要做的是将一个点击事件处理程序绑定到所有的复选框,并且向已被点击的父类label添加/删除类。如果这是正确的,那么你可以这样做:

$("input[type='checkbox']").change(function() { 
    $(this).closest("label").toggleClass("someClass"); 
}); 

toggleClass方法消除了需要检查的复选框是否被选中。你可以通过在第二个参数显示类是否应该被添加或删除,因此,如果你的一些复选框开始已经检查,你可能要使用:

$("input[type='checkbox']").change(function() { 
    $(this).closest("label").toggleClass("someClass", this.checked); 
}); 

这里的一个working example以上代码。

+0

谢谢,这有助于解决添加和删除类的问题。我会发布另一个问题,当我检查并取消选中这些框时,如果更改“清单”的数组值,会发生什么情况。 – ssdesign