<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
<style>
*{
margin:0;
padding: 0;
}
.active{
background: red;
}
#main p{
width: 200px;
height: 200px;
background: yellow;
display: none;
}
</style>
<script>
window.onload=function()
{
var op = document.getElementById('main');
var oIp = op.getElementsByTagName('input');
var ap = op.getElementsByTagName('p');
for(var i=0;i<oIp.length;i++)
{
oIp[i].index=i;
oIp[i].onclick=function()
{
for(var i=0;i<oIp.length;i++) // 就是这儿
{
oIp[i].className="";
ap[i].style.display="";
}
this.className="active";
ap[this.index].style.display="block"
}
}
}
</script>
</head>
<body>
<p id="main">
<input class="active" type="button" value="111">
<input type="button" value="222">
<input type="button" value="333">
<input type="button" value="444">
<p style="display: block">1</p>
<p>2</p>
<p>3</p>
<p>4</p>
</p>
</body>
</html>
This is an example of a tab on the Internet, but I don’t quite understand the js part of the example and what the second for loop means. . . QAQ
The outer layer of for is mainly to bind the
onclick
event to each tab button.The for inside is within the bound
onclick
event. Its function is,When clicks the bound tab, it traverses all the tabs and selects the options that are not currently clicked. The cards are reset to the hidden state, and then this
for
below:is to display the tab corresponding to the currently clicked item.
In this way, only the tab corresponding to the currently clicked item will be displayed, and the rest of the tabs will be hidden.
Without this for, when you click on the first label, the first label will be displayed.
Then you clicked the second tab, the second tab was displayed, and now the first and second tabs are displayed at the same time;
Then you clicked the third tab, the first two were not hidden, and the Three tabs are displayed...
In this way, in the end, when you click all the tab buttons, all tabs are displayed. This is obviously not the effect of tabs.
In order to hide all tabs except the currently clicked tab, before displaying the current tab, use
for
to traverse and hide all tabs.The general function is to switch to the tab by clicking on it.
The so-called switching means other hidden and currently displayed.
And the part you mentioned is to hide all inputs.
That is, every time you click Yes, all inputs are traversed once, remove the class and display attributes, and hide them.
Then just add this, that is, the current clicked item with class and display attributes, and display them.
I comment the code, and you will know it when you see the comments! The principle of the code is to first clear the class names of all inputs and hide all p's, then add the class name to the currently clicked input and display the p corresponding to the current index!