JavaScript显示/隐藏html元素

时间:2018-06-01 11:50:32

标签: javascript

有没有更简洁的方法在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";
    } 

2 个答案:

答案 0 :(得分:2)

避免所有可能的内联样式和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>
&#13;
&#13;
&#13;

希望它有所帮助。

答案 1 :(得分:0)

这不是很干净,但至少可以节省一些代码。

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

&#13;
&#13;
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";
}
&#13;
<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>
&#13;
&#13;
&#13;