单击新按钮时如何关闭所有其他div?

时间:2019-04-22 20:19:15

标签: javascript jquery html

我有一个包含5个按钮的按钮组。我想要按钮的onclick事件来切换5个不同的div。单击按钮1打开/关闭div 1,单击按钮2打开/关闭div 2,依此类推。 div只是此处的文本。

第一次单击按钮->显示div 第二次单击按钮->隐藏div

但是,当我只单击一个按钮一次并且它的div出现,而我单击另一个按钮时,另一个div会堆叠在第一个div的顶部。如果单击两次其第一按钮,则可以关闭它,但是即使单击另一个按钮,我也希望该divs关闭。我该如何实现?

到目前为止,我已经将jsfiddle附加了。

我几次看到类似的问题,但没有一个解决方案适合我。任何帮助将不胜感激。

  function togglediv(id) {
            var div = document.getElementById(id);
            div.style.display = div.style.display == "none" ? "block" : "none";
        }
<div class="myButtons">
  <div class="btn-group" id="MatchingEntitiesButtons">

  <button id="Button1" class="roundBtns" onclick="togglediv('NamesTable')" type="button" > List of Names </button>

  <button id="Button2" class="roundBtns" onclick="togglediv('PhoneTable')" type="button"> List of Address </button>

  <button  id="Button3" class="roundBtns" onclick="togglediv('AddressTable')" type="button" > List of Phone#</button>

  <button id="Button4" class="roundBtns" onclick="togglediv('GradesTable')" type="button"> List of Grades</button>

  <button id="Button5" class="roundBtns" onclick="togglediv('SchoolTable')" type="button"> List of Schools </button>  

  </div>
</div>

<div id ="NamesTable" class="TableBody" style="display:none">Names </div>
<div id ="PhoneTable" class="TableBody" style="display:none">Address </div>
<div id ="AddressTable" class="TableBody" style="display:none">Phone# </div>
<div id ="GradesTable" class="TableBody" style="display:none">Grades </div>                  
<div id ="SchoolTable" class="TableBody" style="display:none">School </div>

4 个答案:

答案 0 :(得分:0)

使用课程会让这变得容易得多。您可以选择具有活动类的元素并将其删除。

function togglediv(id) {

  var div = document.getElementById(id);

  document.querySelectorAll(".TableBody.active").forEach(function(elem) {
    if (elem !== div) elem.classList.remove("active");
  });

  // toggle the class to the section that was clicked.
  div.classList.toggle("active");

}
.TableBody {
  display: none;
}

.TableBody.active {
  display: block;
}
<div class="myButtons">
  <div class="btn-group" id="MatchingEntitiesButtons">

    <button id="Button1" class="roundBtns" onclick="togglediv('NamesTable')" type="button"> List of Names </button>

    <button id="Button2" class="roundBtns" onclick="togglediv('PhoneTable')" type="button"> List of Address </button>

    <button id="Button3" class="roundBtns" onclick="togglediv('AddressTable')" type="button"> List of Phone#</button>

    <button id="Button4" class="roundBtns" onclick="togglediv('GradesTable')" type="button"> List of Grades</button>

    <button id="Button5" class="roundBtns" onclick="togglediv('SchoolTable')" type="button"> List of Schools </button>

  </div>
</div>

<div id="NamesTable" class="TableBody">Names </div>
<div id="PhoneTable" class="TableBody">Address </div>
<div id="AddressTable" class="TableBody">Phone# </div>
<div id="GradesTable" class="TableBody">Grades </div>
<div id="SchoolTable" class="TableBody">School </div>

无需使用该类,您就可以使用循环并将其设置为隐藏

document.querySelectorAll(".TableBody")
  .forEach(function (elem) {
    elem.style.display = "none";
  })

此代码不会切换。如果需要切换,只需检查该元素是否为当前元素即可。

var active = doucument.getElementById(id);
document.querySelectorAll(".TableBody")
  .forEach(function (elem) {
    if (elem !== active) {
      elem.style.display = "none";
    }
  })

答案 1 :(得分:0)

遍历所有DIV。如果它是指定的DIV,请切换它,否则将其隐藏。

var salesorderSearchObj = search.create({
    type: "salesorder",
    filters:
    [
        ["type","anyof","SalesOrd"], 
        "AND", 
        ["internalid","anyof",12345], 
        "AND", 
        ["taxline","is","F"], 
        "AND", 
        ["cogs","is","F"], 
        "AND", 
        ["shipping","is","F"], 
        "AND", 
        ["mainline","is","T"]
    ],
    columns:
    [
        search.createColumn({
            name: "trandate",
            sort: search.Sort.ASC,
            label: "Date"
        }),
        search.createColumn({
            name: "internalid",
            join: "file",
            label: "Internal ID"
        }),
        search.createColumn({
            name: "url",
            join: "file",
            label: "URL"
        }),
        search.createColumn({
            name: "url",
            join: "lineFile",
            label: "URL"
        })
    ]
});
var searchResultCount = salesorderSearchObj.runPaged().count;
salesorderSearchObj.run().each(function(result){
    var fileId = result.getValue({
        name: "internalid",
        join: "file",
        label: "Internal ID"
    });

    var fileObj = file.load({id: fileId});
    return true;
});
function togglediv(id) {
  document.querySelectorAll(".TableBody").forEach(function(div) {
    if (div.id == id) {
      // Toggle specified DIV
      div.style.display = div.style.display == "none" ? "block" : "none";
    } else {
      // Hide other DIVs
      div.style.display = "none";
    }
  });
}

答案 2 :(得分:0)

在单击任意按钮时隐藏所有div元素,然后仅显示需要显示的元素。

但是,稍微改变一下方法:

  • 请勿使用内联HTML事件属性,例如onclick。有 a bunch of reasons不要使用这种25岁以上的技术 不会死。
  • 使用Event Delegation可以设置单个事件处理程序,但是 根据点击的特定按钮做出反应。
  • 摆脱id s。使用id会使代码变脆,因为您 需要不断更新代码以考虑新元素。
  • 不使用内联样式--使用CSS类。这消除了 冗余代码,使覆盖应用样式更加容易。

var clickedBtnIndex = null;
var shownDiv = null;

// Get all the buttons and divs into Arrays:
let buttons = Array.prototype.slice.call(document.querySelectorAll(".roundBtns"));
let divs = Array.prototype.slice.call(document.querySelectorAll(".TableBody"));

// Set up a single click event handler on the parent element of the buttons
document.querySelector(".btn-group").addEventListener("click", function(evt){ 

  // evt.target is a reference to the specific button that triggered the event
  clickedBtnIndex = buttons.indexOf(evt.target); // Get the index of the clicked button within its group

  // If a button was clicked
  if(evt.target.classList.contains("roundBtns")){
     
     // Loop over the divs
     divs.forEach(function(div){
        // Check to see if it is currently being shown
        if(!div.classList.contains("hidden")){
           shownDiv = div;
        }
     });
  
     hideAll();  // Hide all the divs
     
     // Show/hide just the one that was clicked
     if(divs[clickedBtnIndex] === shownDiv){
       divs[clickedBtnIndex].classList.add("hidden");
       shownDiv = null;
     } else {
       divs[clickedBtnIndex].classList.remove("hidden");  
     }
     
     // Store a reference to the index of the button within its group that was clicked
     clickedBtnIndex = buttons.indexOf(evt.target);
  }

});

// This will hide all the divs
function hideAll(){
  // Loop over the array
  divs.forEach(function(div){
    div.classList.add("hidden");  // Add the hidden class
  });
}
.hidden { display:none; }
<div class="myButtons">
  <div class="btn-group" id="MatchingEntitiesButtons">
    <button class="roundBtns" type="button">List of Names</button>
    <button class="roundBtns" type="button">List of Address</button>
    <button class="roundBtns" type="button">List of Phone#</button>
    <button class="roundBtns" type="button">List of Grades</button>
    <button class="roundBtns" type="button">List of Schools</button>  
  </div>
</div>

<div class="TableBody hidden">Names</div>
<div class="TableBody hidden">Address</div>
<div class="TableBody hidden">Phone#</div>
<div class="TableBody hidden">Grades</div>                  
<div class="TableBody hidden">School</div>

但是要真正简单得多,请摆脱要显示或隐藏的单独div,而只使用一个div作为占位符即可。然后,只需更改单个div的内容即可。

// Store the data that will need to be displayed in an object that
// has properties that store the arrays of actual data
var data = {
  names: ["Scott","Mary","Tom"],
  addresses: ["10 Main", "23 Elm", "43 Standish"],
  phoneNums: ["555-555-5555","123-456-7890"],
  grades: ["C", "B-", "A+"],
  schools: ["District 1", "District 2", "District 3"]
};

// These map to the object properties and will be used to extract the right data
var keyNames = ["names", "addresses", "phoneNums", "grades", "schools"];

var output = document.querySelector(".output"); // The output element

// Get all the buttons and divs into Arrays:
let buttons = Array.prototype.slice.call(document.querySelectorAll(".roundBtns"));

// Set up a single click event handler on the parent element of the buttons
document.querySelector(".btn-group").addEventListener("click", function(evt){

  // Get the index of the button that was clicked within its group
  var clickedIndex = buttons.indexOf(evt.target);
  
  // Inject the string into the output div
  output.innerHTML = data[keyNames[clickedIndex]].join("<br>");;
});
<div class="myButtons">
  <div class="btn-group" id="MatchingEntitiesButtons">
    <button class="roundBtns" type="button">List of Names</button>
    <button class="roundBtns" type="button">List of Address</button>
    <button class="roundBtns" type="button">List of Phone#</button>
    <button class="roundBtns" type="button">List of Grades</button>
    <button class="roundBtns" type="button">List of Schools</button>  
  </div>
</div>

<div class="output"></div>

而且,要真正降低复杂性,请不要为每个要单击的按钮使用单独的div。只需一个div,然后根据要单击的按钮更改其中的内容即可:

答案 3 :(得分:-2)

我试图通过标签和类名来操纵样式,但是显然这是行不通的。

因此,我编写了更大的代码。我将所有显示设置为“无”,将选定的显示设置为“阻止”:

这是html:

<div class="myButtons">
    <div class="btn-group" id="MatchingEntitiesButtons">

    <button id="Button1" class="roundBtns" onclick="togglediv('NamesTable')" type="button" > List of Names </button>

    <button id="Button2" class="roundBtns" onclick="togglediv('PhoneTable')" type="button"> List of Address </button>

    <button  id="Button3" class="roundBtns" onclick="togglediv('AddressTable')" type="button" > List of Phone#</button>

    <button id="Button4" class="roundBtns" onclick="togglediv('GradesTable')" type="button"> List of Grades</button>

    <button id="Button5" class="roundBtns" onclick="togglediv('SchoolTable')" type="button"> List of Schools </button>  

    </div>
</div>

<div id ="NamesTable" class="TableBody" style="display:none">Names </div>
<div id ="PhoneTable" class="TableBody" style="display:none">Address </div>
<div id ="AddressTable" class="TableBody" style="display:none">Phone# </div>
<div id ="GradesTable" class="TableBody" style="display:none">Grades </div>                  
<div id ="SchoolTable" class="TableBody" style="display:none">School </div>

这是JS:

function togglediv(id) {
    var div = document.getElementById(id);

    if (id == "NamesTable") {
        document.getElementById("NamesTable").style.display = "block";
        document.getElementById("AddressTable").style.display = "none";
        document.getElementById("PhoneTable").style.display = "none";
        document.getElementById("GradesTable").style.display = "none";
        document.getElementById("SchoolTable").style.display = "none";

    } else if (id == "PhoneTable") {
        document.getElementById("NamesTable").style.display = "none";
        document.getElementById("PhoneTable").style.display = "block";
        document.getElementById("AddressTable").style.display = "none";
        document.getElementById("GradesTable").style.display = "none";
        document.getElementById("SchoolTable").style.display = "none";

    } else if (id == "AddressTable") {
        document.getElementById("NamesTable").style.display = "none";
        document.getElementById("PhoneTable").style.display = "none";
        document.getElementById("AddressTable").style.display = "block";
        document.getElementById("GradesTable").style.display = "none";
        document.getElementById("SchoolTable").style.display = "none";

    } else if (id == "GradesTable") {
        document.getElementById("NamesTable").style.display = "none";
        document.getElementById("PhoneTable").style.display = "none";
        document.getElementById("AddressTable").style.display = "none";
        document.getElementById("GradesTable").style.display = "block";
        document.getElementById("SchoolTable").style.display = "none";

    } else {
        document.getElementById("NamesTable").style.display = "none";
        document.getElementById("PhoneTable").style.display = "none";
        document.getElementById("AddressTable").style.display = "none";
        document.getElementById("GradesTable").style.display = "none";
        document.getElementById("SchoolTable").style.display = "block";

    }
}