Jquery hide() 除了一个类之外的所有元素

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/10612379/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 09:35:39  来源:igfitidea点击:

Jquery hide() all elements with certain class except one

jquery

提问by lisovaccaro

<div class='hide'>A</div>
<div class='hide'>B</div>
<div class='hide' id='1'>C</div>

I have a function called showOne which should hide all elements and then show the one with id='1'.

我有一个名为 showOne 的函数,它应该隐藏所有元素,然后显示 id='1' 的元素。

function showOne(id) {
// Hide all elements with class = 'hide'
$('#'+id).show();
}

How do I hide all elements with class = 'hide' in jquery?

如何在 jquery 中隐藏 class = 'hide' 的所有元素?

回答by Ayman Safadi

Try something like:

尝试类似:

function showOne(id) {
    $('.hide').not('#' + id).hide();
}

showOne(1);?

Demo: http://jsfiddle.net/aymansafadi/kReZn/

演示:http: //jsfiddle.net/aymansafadi/kReZn/

I agree with @TheSystemRestart though, "NOTE: DON'T USE ONLY NUMERIC ID".

我同意@TheSystemRestart,“注意:不要只使用数字 ID”。

回答by The System Restart

$('div.hide').hide(300,function() {  // first hide all `.hide`
   $('#'+ id +'.hide').show(); // then show the element with id `#1`
});

NOTE: DON'T USE ONLY NUMERIC ID. NOT PERMITTED. READ THIS

注意:不要只使用数字 ID。不允许。读这个

回答by Hitesh Modha

You have to access elements by css class name. To do this use .operator

您必须通过 css 类名访问元素。要做到这一点,请使用. 操作员

$('.hide').hide();

It will hide all divs.

它将隐藏所有 div。

Now show one div by id;

现在按 id 显示一个 div;

$('#elemID').show();

Or you can also do this by using

或者您也可以使用

$('.hide').eq(0).show();

It will show first div having class hide.

它将显示第一个具有类hide 的div 。

回答by HGK

Try:

尝试:

function showOne(id) { 
    $('.hide').hide();
    $('#'+id).show(); 
} 

回答by lisovaccaro

I'm almost ashamed of how easy the solution was and that I found it just after writing the question. Just:

我几乎为解决方案如此简单而感到羞耻,而且我在写完问题后就找到了它。只是:

$('.hide').hide();

回答by Ankur Verma

You can hide all components with class as hide using .$('.hide').hide();

您可以使用隐藏类隐藏所有组件$('.hide').hide();