2011-04-05 56 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')); 
});