JQuery hide Class if other class is visible or shown

戏子无情 提交于 2019-12-24 01:53:22

问题


Found similar questions but nothing that covers exactly what I need. I kept it simple in my example and I want to use JQuery.

I have two classes. I want to hide the "filter" div if the "category" div is shown on page load. There are currently NO styles associated with either class. I believe I am pretty close but it doesn't work.

<script language="text/javascript">
if(!$(this).hasClass("category")){
$('filter').css('display', 'none');
}
</script>

<div class="category">By Category</div>
<div class="filter">By Custom Filter</div>

Thanks in advance!


回答1:


Use .length to test if an element is present.

Use .hide() & .show() to show and hide elements.

And finally, you want the code to run only when the page has finished loading, so you want to wrap it all in $(document).ready().

So something like this should work best:

<script language="text/javascript">
    $(document).ready(function() {
        //following code will hide all elements with a class of 'filter'
        //if any elements with a class of 'category' are found
        if($('.category').length){
            $('.filter').hide();
        }
    });
</script>

<div class="category">By Category</div>
<div class="filter">By Custom Filter</div>

HTHs,
Charles




回答2:


Change the selector to $('.filter')




回答3:


var $filter = $(".filter");
var $category = $(".category");

$category.is(":visible") ? $filter.hide() : $filter.show();



回答4:


jQuery

$('div').each(function() {
    if ($(this).hasClass("category")) {
        $('.filter').css('display', 'none');
    }
});

or just:

if ($('.category').length) {
    $('.filter').css('display', 'none');
}



回答5:


 <div class="category">By Category</div>
 <div class="filter">By Custom Filter</div>

Assuming by "shown on page load" you mean rendered and not the show/hide visibility.

$('.category').each(function(){
    $('.filter').hide();
});


来源:https://stackoverflow.com/questions/4318391/jquery-hide-class-if-other-class-is-visible-or-shown

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!