2011-04-05 80 views
1

我有以下的HTMLAddClass使用jQuery目标需要帮助

<fieldset> 
    <legend> 
    <input type="checkbox" class="myCheck">Click 
    </legend> 
    content 
<fieldset> 

我想选中该复选框时添加类和删除选中的时候。应该像这样的工作:

$(".myCheck").change(function() {   
    if ($(this).is(':checked')){ 
     $(this).parent("fieldset").addClass("myClass"); 
    } else { 
     $(this).parent("fieldset").removeClass("myClass"); 
    } 
}); 

我错过了什么?

回答

2

.parent()只能遍历一级。 但是,根据HTML你已经fieldset是两个层次。 使用父母或最近。

即:

$(".myCheck").change(function() {     
    if ($(this).is(':checked')){   
     $(this).closest("fieldset").addClass("myClass");  
     } else {   
     $(this).closest("fieldset").removeClass("myClass");  
    } 
}); 

$(".myCheck").change(function() {     
    if ($(this).is(':checked')){   
     $(this).parents("fieldset").addClass("myClass");  
     } else {   
     $(this).parents("fieldset").removeClass("myClass");  
    } 
}); 
1

.parent()会给你在这种情况下,直接父是<legend/>你既可以做.parent().parent("fieldset")或使用.parents("fieldset")但是,这将使你的任何父$(this)匹配<fieldset/>

把它GETHER你就会有这样的事情:

$(this).parent().parent("fieldset").addClass("myClass"); 

$(this).parents("fieldset").first().addClass("myClass"); 


您也可以使用.toggleClass(className, switch)

$(".myCheck").change(function() {   
    $(this).parents("fieldset").first().toggleClass("myClass", $(this).is(':checked')); 
}); 

Code example on jsfiddle

1

试试这个出:

$('.myCheck').click(function() { 
    $(this).closest('fieldset').toggleClass('myClass', $(this).is(':checked')); 
});