JavaScript 显示/隐藏为 div 列表的过滤器

JavaScript Show/Hide as Filters to list of divs(JavaScript 显示/隐藏为 div 列表的过滤器)

本文介绍了JavaScript 显示/隐藏为 div 列表的过滤器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

希望创建类似于 div 列表过滤器的 Javascript.例如,这是预期的标记...

Looking to create Javascript that acts like a filter on a list of divs. For instance, here's the intended markup...

<a href="#" onclick="">Filter Item 1</a>
<a href="#" onclick="">Filter Item 2</a>
<a href="#" onclick="">Filter Item 3</a>
<a href="#" onclick="">Filter Item 4</a>
<a href="#" onclick="">Filter Item 5</a>

<div class="1">Item 1</div>
<div class="1">Item 1</div>
<div class="2">Item 2</div>
<div class="3">Item 3</div>
<div class="1">Item 1</div>
<div class="4">Item 4</div>
<div class="4">Item 4</div>
<div class="1">Item 1</div>
<div class="5">Item 5</div>

我希望能够点击第 1 项的链接,只显示第 1 项 div 并隐藏所有其他 div,单击第 2 项的链接,只显示第 2 项 div 并隐藏所有其他 div 等等.我见过几个类似的脚本,但似乎没有以这种方式打开/关闭匹配类的 div.

I want to be able to click on the link for Item 1, and show only Item 1 divs and hide all other divs, click the link of Item 2, and show only Item 2 divs and hide all other divs and so on. I've seen several similar scripts but nothing that seemingly turns divs matching the class on/off in this manner.

推荐答案

这可以在 jquery 中轻松完成,如下应该适合你,但你必须修改你的 html 如下

This can be done easily in Jquery, following should work for you, but you have to modify your html as following

<a href="#" class="link" id="1">Filter Item 1</a>
<a href="#" class="link" id="2">Filter Item 2</a>
<a href="#" class="link" id="3">Filter Item 3</a>
<a href="#" class="link" id="4">Filter Item 4</a>
<a href="#" class="link" id="5">Filter Item 5</a>

<div class="1">Item 1</div>
<div class="1">Item 1</div>
<div class="2">Item 2</div>
<div class="3">Item 3</div>
<div class="1">Item 1</div>
<div class="4">Item 4</div>
<div class="4">Item 4</div>
<div class="1">Item 1</div>
<div class="5">Item 5</div>

和javascript如下

and javascript as follows

$(document).ready(function(){
 $(".link").click(function(e){
  $("." + e.currentTarget.id).toggle()
 }
});

这篇关于JavaScript 显示/隐藏为 div 列表的过滤器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本文标题为:JavaScript 显示/隐藏为 div 列表的过滤器

基础教程推荐