JS(循环):找到完美的过滤循环



今天,我开始了一项非常简单的任务,随着我做得越多,它就会成为一个问题。你看,我正在尝试制作一个JS功能侧边栏,它将根据每个元素中的过滤属性过滤容器中的元素。如果它是(过滤规则(的一部分,则应显示该元素。否则,它应该不显示任何

<ul id="filteringSidebar">
  <li>Color Is Green</li>
  <li>Color Is Yellow</li>
  <li>Color Is Blue</li>
  <li>Color Is Violet</li>
  <li>Color Is Magenta</li>
  <li>Color Is Orange</li>
  <li>Color Is Indigo</li>
  <li>Color Is Gray</li>
  <li>Color Is Black</li>
</ul>
<div id="elementsContainer">
  <div> Blue </div>
  <div> Magenta </div>
  <div> Magenta </div>
  <div> Yellow </div>
  <div> Blue </div>
  <div> Orange </div>
  <div> Orange </div>
  <div> Indigo </div>
  <div> Blue </div>
  <div> Gray </div>
  <div> Blue </div>
  <div> Black </div>
  <div> Orange </div>
</div>

这是对我目标实现的目标的非常原始的解释,但整个想法是让人们能够单击 UL 中 ID 为 filteringSidebar 的一个或多个列表项,并根据用户输入期望结果。(如果按下黄色和橙色,则 DIV 中应仅显示 ID 为 elementsContainer 的黄色和橙色元素(

在这里,

我为每个<li>项目提供了一个不同的 id,然后使用引导程序进行样式设置。然后每个<div>通过使用引导d-none隐藏。使用查询每个按钮都分配给不同的功能,这些功能将切换d-none。这只是一个基本的,可能有更简单的方法可以做到这一点。

<html>
<head>
</head>
<!-- Latest compiled and minified CSS -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css">
<!-- jQuery library -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<div class="container">
  <script>
    function showDivGreen() {
      $("#green").each(function() {
        $('#green').toggleClass('d-none');
      })
    }
    function showDivYellow() {
      $('#yellow').toggleClass('d-none');
    }
    function showDivBlue() {
      $('#blue').toggleClass('d-none');
    }
  </script>
  <ul id="filteringSidebar">
    <button class="btn btn-success" id="btnGreen" onclick="showDivGreen();" value="green"><li>Color Is Green</li> </button>
    <button class="btn btn-warning" id="btnYellow" onclick="showDivYellow();" value="yellow"><li>Color Is Yellow</li>
<button class="btn btn-primary" id="btnBlue" onclick="showDivBlue();" value="blue"><li>Color Is Blue</li>
</ul>
<div class="row">
<div id="blue" class="bg bg-primary col-md-4 hidden d-none " > Blue </div>
<div id="yellow"   class="bg bg-warning  col-md-4 d-none" > Yellow </div>
<div  id="green"   class="bg bg-success col-md-4 d-none" > Green </div>
</div>
</div>
</body>
</html>

最新更新