[英]JavaScript show / hide html elements
有沒有更干凈的方法可以在JavaScript中實現這一點,我正在嘗試基於click函數顯示/隱藏項目
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>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.