如果 div 没有类名,则隐藏它。

3
我正在尝试创建一个包含不同标签(例如代码设计)的作品集 - 然后我想在顶部添加一个导航,当您单击“代码”时,它将隐藏除了带有类名代码的所有div之外的所有div。并且对于设计也是如此。 我已经看到一些使用.not jQuery函数的示例,但我无法使其与我的代码配合工作。
<a id="code-btn" href="#"> Show Code </a>
<a id="design-btn" href="#"> Show Design </a>

<div class="box d">test</div>
<div class="box c">test</div>
<div class="box d">test</div>

<script>
    $("#code-btn").click(function() {
        $('div').not('.' + c).hide();
    });
</script>

我不想使用切换按钮,因为以后可能会添加更多的标签,例如徽标等。


6
由于没有变量c,所以应该使用.c而不是'.' + c。建议使用$('div.box:not(.c)') - Tushar
你为什么要这样做?只需要隐藏“d”:$('.d').hide(); - Aziz
$('.d').hide(); 能行吗? - Scott
OP可能有其他的类,只需要显示特定类的div。因此,使用not会比逐个隐藏更好。 - guradio
@Tushar 我已经用 $("#code-btn").click(function() { $('div.box').not('.c').hide() }); 让它正常工作了。谢谢!!! - Lucy MacGregor
其实...你完全不需要js来完成这个... - junkfoodjunkie
5个回答

1
尝试像这样做: $("div").filter(":not('.c')").hide();

1
“.c” 需要用双引号括起来。 - Scott Marcus
现在,.c 需要用单引号括起来。 - Scott Marcus
不需要在:not()选择器内使用引号。http://www.w3schools.com/jquery/sel_not.asp - Vagharsh
W3Schools应该持保留态度。:not(.a .b)会如何运作? - Scott Marcus

0

这里 - 仅使用CSS完成,完全不需要JS。

.button {
  margin: 0 2em;
  }

div {
  display: none;
  }
div:target {
  display: block;
  }
<a class="button" id="code-btn" href="#code"> Show Code </a>
<a class="button" id="design-btn" href="#design"> Show Design </a>

<div id="code">Code</div>
<div id="design">Design</div>


注意:只能使用一个容器,并且顺序固定(不能有 box c + box d + box c)。 - Aziz
没错,但在这种特殊情况下,你为什么要这样做呢? - junkfoodjunkie

0

移除类别的连接...

看看这个...可能会有帮助...

$("#code-btn").click(function() {
        $('div').not('.c').hide();
    });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<a id="code-btn" href="#"> Show Code </a>
<a id="design-btn" href="#"> Show Design </a>

<div class="box d">test d</div>
<div class="box c">test c</div>
<div class="box a">test a</div>


0

我认为这就是你需要的,请查看下面的片段

$(function(){
$('#code-btn').on('click', function(){
 if($('.box').hasClass('c')){
  $('.c').css('display','block'); 
  $('.d').css('display','none');
 }
});
$('#design-btn').on('click', function(){
 if($('.box').hasClass('d')){
  $('.d').css('display','block'); 
  $('.c').css('display','none');
 }
});
});
.box {
 display:none;
}
<a id="code-btn" href="#"> Show Code </a>
<a id="design-btn" href="#"> Show Design </a>

<div class="box d">design</div>
<div class="box c">code</div>
<div class="box d">design</div>


<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>


0

我的版本同时使用一个事件处理程序

       $("a").click(function (evt) {
                var showCode = this.id == "code-btn";
                $("div.c").toggle(showCode);
                $("div.d").toggle(!showCode);
            }
                )
        });

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接