javascript jQuery 仅在有类时才显示 div
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/32140653/
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
jQuery show div only if has class
提问by Donnie
I have some problems with show/hide element. I have 2 popups on one page and I need hide one popup if another popup has class. For example:
我对显示/隐藏元素有一些问题。我在一个页面上有 2 个弹出窗口,如果另一个弹出窗口有类,我需要隐藏一个弹出窗口。例如:
<body class="home">
<div class="popup main"></div>
<div class="popup"></div>
</body>
So, if body.homehas .mainI need to show only .mainpopup and hide or remove another .popup.
所以,如果body.home有.main我只需要显示.main弹出窗口并隐藏或删除另一个.popup。
I'va tried
我试过了
if ($('.home').find('.main')) {
$('.home').find('.main').show();
$('.home').find('.popup').remove();
}
But it does not working as I need, because in some reason I'll have code only with one popup block
但它不能按我的需要工作,因为出于某种原因,我的代码只有一个弹出块
<body class="home">
<div class="popup"></div>
</body>
回答by Sathish
Just try this,
试试这个,
if($(".popup").hasClass('main')){
$(".popup").hide();
$(".main").show();
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<body class="home">
<div class="popup main">main</div>
<div class="popup">another</div>
</body>
回答by vijayP
$( '.home .popup' ).not( ".main" ).remove();
回答by Artur Filipiak
You may want something like this:
你可能想要这样的东西:
$('.popup.main').length &&
$('.popup').show().not('.main').remove() ||
$('.popup').show();
The above code is basically a "shortcut" of this:
上面的代码基本上是这个的“捷径”:
// if there's a popup with class .main:
if($('.popup.main').length){
// show it:
$('.popup.main').show();
// and remove the one without class .main:
$('.popup').not('.main').remove();
// else, if there's no popup with class .main:
}else{
// show the .popup:
$('.popup').show();
}
回答by Octavian Lari
check with hasClass()
检查 hasClass()
if ($('.home .popup').hasClass('main')) {
$('.home .popup').hide();
$('.home .main').show();
}
This will hide all popups, then show only that has .main
class
这将隐藏所有弹出窗口,然后仅显示具有.main
类的
Edit
编辑
ok this in not working when .home has only one child.
Try solving this with css
好的,这在 .home 只有一个孩子时不起作用。尝试解决这个问题css
.home .popup:not(.main) {
display: none;
}
.home .popup:only-child {
display: block !important;
}
with this code you only have to add/remove .main
class to manage visibility
使用此代码,您只需添加/删除.main
类即可管理可见性
回答by Quan Nguyen
If you want to show/hide element, use jQuery.hide()
or jQuery.show()
. If you use jQuery.remove()
then u don't have chance to do it again because it was removed from DOM tree.
如果要显示/隐藏元素,请使用jQuery.hide()
或jQuery.show()
。如果您使用,jQuery.remove()
那么您将没有机会再次使用它,因为它已从 DOM 树中删除。