javascript - 如何根据用户在下拉列表中的选择显示特定的 HTML 元素
问题描述
我有一个由两个条形图组成的 HTML 页面。如何在默认情况下隐藏这两个图表,根据用户在下拉菜单中的选择,“选择”选项一次只显示 1 个元素?
HTML:
<input type="number" id="options" value="" style="display:none">
<select id="option">
<option>select</option>
<option id="option-salary"> Sort by Salary </option>
<option id="option-age"> Sort by Age </option>
</select>
</input>
<div id="bar-chart">
<div class="salary-chart chart-container ">
<div class="names" id="salary-names"></div>
<div class="chart" id="salary-chart"></div>
</div>
<div class="age-chart chart-container ">
<div class="names" id="age-names"></div>
<div class="chart" id="age-chart"></div>
</div>
</div>
CSS
.chart-container{
display: flex;
padding: 20px;
min-height: 100%;
}
.chart{
border: 1px black solid;
width: 500px;
}
.salary{
margin: 20px;
}
.age{
margin: 20px;
}
.name{
margin: 20px;
}
先感谢您!
解决方案
为此,您将需要使用 Javascript,但让我们从您的 Html 标记开始: 首先- 我们必须从 select 元素周围删除输入标记,因为它不是必需的。 第二- 我们将给每个值一个特定的值(年龄选项的“年龄”和“薪水”选项的工资)
<select id="option">
<option>select</option>
<option id="option-salary" value="salary"> Sort by Salary </option>
<option id="option-age" value="age"> Sort by Age</option>
</select>
一个我们给选项的值然后我们将两个图表的显示设置display : none
为 Css
.chart-container {
display: none;
}
现在我们将在 javascript 中设置事件 onchange 以卡车选项中的任何更改,然后根据所做的选择显示一个图表
将此脚本添加到您的 Javascript 文件
//get the Elements from the Html Document
let sortInput = document.getElementById('option'),
salaryCartr = document.querySelector('.salary-chart'),
ageCart = document.querySelector('.age-chart');
//When the sort input changes
sortInput.onchange = function() {
let inputValue = document.getElementById('option').value;
// check the value returned and make the desicion
switch (inputValue) {
case 'age':
salaryCartr.style.display = "none";
ageCart.style.display = "block";
break;
case 'salary':
ageCart.style.display = "none";
salaryCartr.style.display = "block";
break;
default:
ageCart.style.display = "none";
salaryCartr.style.display = "none";
break;
}
}
推荐阅读
- c++ - 试图将 txt 文档分解为一组值
- mysql - 实现评论和喜欢系统(如 Instagram 或 Twitter)的最佳方法
- dotnetbrowser - DotNetBrowser 在使用客户标头时使用 GET 而不是 POST
- python - 用年份和年份计算的 Python 日期不正确
- javascript - 遍历父 div 子元素并关闭该 div 并打开一个新 div 继续循环
- python - Flask - 如何将多个图像上传到数据库并在网站上呈现它们
- google-analytics - Google Analytics - 用户总数不正确
- powershell - 检查是否已配置 nuget 源
- python - 我怎样才能在 python 中关闭一个情节然后重新打开它?
- c# - 使用 winforms (C#) 复制表格的一行