javascript - 如何创建用作过滤器的段落
问题描述
我想知道如何使这段代码更简单、更短。我在 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 循环或类似的东西可以更容易地完成它。
提前感谢您的建议!
解决方案
我讨厌推荐 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>
推荐阅读
- javascript - 为什么 notifyItemChanged(position) 不更新 RecyclerView 中的所有项目?
- python - Python CVXPY 最小化百分位变量投资组合优化
- php - 在 Coda 2 中关闭我的代码中的 P 符号
- python - 如何在 PySimpleGUI 中将 Tree 元素中的选定行从一个选项卡移动到另一个选项卡?
- firebase - Firestore 使用 Flutter 一次性读取,我在控制台中打印文档数据想要在 UI 中输出
- rust - 如何在 vulkano-rs“0.23.0”中创建 AutoCommandBufferBuilder?
- c - 动态内存分配 - 保持段错误
- arrays - 如何使二维数组上的字符随机移动?
- python - 一些 GSM AT 命令有效,一些不返回任何内容
- vb.net - 如何识别图像中的某个区域