1

当我选中一个复选框时,我希望能够隐藏整个容器。

* HTML *

<div class="showIt">
    <div>abc</div>
    <div>123</div>
    <div><input type="checkbox" /></div>
</div>

* CSS *

div.showIt {
    display:inherit;
}
div.hideIt {
    display:none;
}

* JavaScript(它不起作用)*

<script>
jQuery.support.cors = true; // needed for ajax to work in certain older browsers and versions

$(document).ready(function(){

    $(this).change(function(e) {

        $(this).parent().toggleClass('showIt hideIt');

        $(this).closest("div").toggleClass('showIt hideIt');

    });

}); // end .ready()
</script>
4

2 回答 2

2

你在语法上是错误的。

$(this)在您的代码上当时没有选择任何元素。

$("input:checkbox").change(function(e) {
// ^ This here tell to select an input element of type `checkbox` and then attach an event to it
    $(this).parent().toggleClass('hideIt'); 
    //               ^ Here provide show those classes which you want to toggle, giving multiple class does not toggle between them

    $(this).closest("div").toggleClass('hideIt');
    //This is does same thing as above statement

});

你不需要

div.showIt {
    display:inherit;
}

只需切换.hideIt 它就足够了

演示

于 2012-03-12T01:04:39.070 回答
1

@FelixKling 的回答有效。

jQuery.support.cors = true; // needed for ajax to work in certain older browsers and versions

$(document).ready(function(){

$("input:checkbox").change(function(e) {
// ^ This here tell to select an input element of type `checkbox` and then attach an event to it
    //$(this).parent().toggleClass('hideIt'); 
    //               ^ Here provide show those classes which you want to toggle, giving multiple class does not toggle between them -- THIS DID NOT WORK

    //$(this).closest("div").toggleClass('hideIt'); THIS DID NOT WORK EITHER

    $(this).closest("div.showIt").toggleClass('hideIt'); // THIS WORKED

});

}); // end .ready()
于 2012-03-12T01:23:18.650 回答