如何创建充当过滤器的段落

时间:2018-04-24 16:17:41

标签: javascript html css

我想知道如何使这段代码更简单,更短。 我有三个HTML段落用作过滤器。 他们的ID分别是" all"," positive"和"否定"。 他们指的是评论。 在它们下面是三个div,其中包含实际的评论。 它们还带有名称为#34; allcont"," poscont"和" negcont"分别。 这里的想法是当我点击" 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循环或类似的东西可以轻松完成。

提前感谢您的建议!

1 个答案:

答案 0 :(得分:1)

我讨厌推荐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>

相关问题