JavaScript show / hide html elements



有没有更简洁的方法在JavaScript中实现这一点, 我正在尝试根据点击功能显示/隐藏项目

var overview = document.getElementById("overview"); 
var schedule = document.getElementById("schedule");
var reports = document.getElementById("reports");
function btnOverview_Click() {
schedule.style.display = "none";
reports.style.display = "none";
overview.style.display = "block";
}       
function btnSchedule_Click() {
overview.style.display = "none";
reports.style.display = "none";
schedule.style.display = "block";
} 
function btnReports_Click() {
overview.style.display = "none";
schedule.style.display = "none";
reports.style.display = "block";
} 

避免所有可能的内联样式和JavaScript,
我建议你执行以下操作:

// I added a class in your HTML
var elements = document.querySelectorAll(".myClass");
var buttons = document.querySelectorAll(".myButtons");
// Function to hide all "elements" except the one we clicked
function hideExceptThis() {
elements.forEach(elm => elm.style.display = "none");
// Get the value in "data" attribute
var id = this.getAttribute("data"); // "this" refers to the one you clicked
document.querySelector(id).style.display = "block";
}
// On load, bind the above function on click for each element
buttons.forEach(but => but.addEventListener("click", hideExceptThis));
#panel {
border-bottom: 1px solid gray;
background: #eee;
padding: 8px;
}
.myClass {
width: 240px;
height: 40px;
margin: 8px;
padding: 8px;
}
#overview { background-color: #fdd; }
#schedule { background-color: #dfd; }
#reports  { background-color: #ddf; }
<div id="panel">
<button class="myButtons" data="#overview">Only overview</button>
<button class="myButtons" data="#schedule">Only schedule</button>
<button class="myButtons" data="#reports">Only reports</button>
</div>
<div class="myClass" id="overview">Overview</div>
<div class="myClass" id="schedule">Schedule</div>
<div class="myClass" id="reports">Reports</div>

希望对您有所帮助。

这不是很干净,但至少它节省了一些代码行。

this(触发函数的元素(传递给您的函数,并将所有元素设置为display: none;,但将单击的元素设置回display: block;

var overview = document.getElementById("overview");
var schedule = document.getElementById("schedule");
var reports = document.getElementById("reports");
function hide(element) {
overview.style.display = "none";
schedule.style.display = "none";
reports.style.display = "none";
element.style.display = "block";
}
<div id="overview" style="width: 100px; height: 15px; background-color: green" onclick="hide(this)"></div>
<div id="schedule" style="width: 100px; height: 15px; background-color: yellow" onclick="hide(this)"></div>
<div id="reports" style="width: 100px; height: 15px; background-color: blue" onclick="hide(this)"></div>

最新更新