首页 > 解决方案 > 如何创建用作过滤器的段落

问题描述

我想知道如何使这段代码更简单、更短。我在 HTML 中有三个段落用作过滤器。它们的 ID 分别为“全部”、“正”和“负”。他们指的是评论。在它们下面是三个包含实际评论的 div。它们还分别带有名称为“allcont”、“poscont”和“negcont”的 ID。这里的想法是当我点击“all”段落时,只有“allcont”div 应该显示,而没有“postcont”和“negcont”。“正面”段落和“负面”段落也是如此。

这样,我将创建三个显示不同评论的过滤器按钮。

这是代码:

var allcont = document.getElementById("allcont");
var poscont = document.getElementById("poscont");
var negcont = document.getElementById("negcont");
var all = document.getElementById("all");
var positive = document.getElementById("positive");
var negative = document.getElementById("negative");
all.onclick = function(){
    allcont.style.display = "block";
    poscont.style.display = "none";
    negcont.style.display = "none";
    all.style.color = "red";
    positive.style.color = "white";
    negative.style.color = "white";
}
positive.onclick = function(){
    poscont.style.display = "block";
    allcont.style.display = "none";
    negcont.style.display = "none";
    positive.style.color = "red";
    all.style.color = "white";
    negative.style.color = "white";  
}
negative.onclick = function(){
    negcont.style.display = "block";
    poscont.style.display = "none";
    allcont.style.display = "none";
    negative.style.color = "red";
    all.style.color = "white";
    positive.style.color = "white";
}

单击任何段落时,它应该将颜色更改为红色,正如我在上面的代码中所写的那样。

这可行,但看起来非常丑陋和复杂,我相信使用 for 循环或类似的东西可以更容易地完成它。

提前感谢您的建议!

标签: javascripthtmlcss

解决方案


我讨厌推荐 jQuery,但是有了 jQuery,它会变得更简单。

$(function(){
  $(".pfilter").on("click", function(){
    var $this = $(this);
    $(".cont").hide();
    $("#"+$this.data("show")).show();
    $(".pfilter").css("color", "blue");
    $this.css("color", "red");
  });
});
p {
  cursor: pointer;
  display: inline-block;
  margin: 0 10px;
  color: blue;
}

div.cont {
  display: none;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p id="all" data-show="allcont" class="pfilter">ALL</p>
<p id="positive" data-show="poscont" class="pfilter">POSITIVE</p>
<p id="negative" data-show="negcont" class="pfilter">NEGATIVE</p>
<hr>
<div id="allcont" class="cont">ALLCONT DIV</div>
<div id="poscont" class="cont">POSTCONT DIV</div>
<div id="negcont" class="cont">NEGCONT DIV</div>


推荐阅读