我已到处搜索“猴级”解释并找不到任何地方。我正在学习JS,并且试图在页面内创建制表符,除了我无法理解W3SCHOOLS示例中的一段代码之外,一切都很好。Javascript选项卡 - For循环说明
HTML:
<div class="tab">
<button class="tablinks" onclick="openCity(event, 'London')">London</button>
<button class="tablinks" onclick="openCity(event, 'Paris')">Paris</button>
<button class="tablinks" onclick="openCity(event, 'Tokyo')">Tokyo</button>
</div>
<div id="London" class="tabcontent">
<h3>London</h3>
<p>London is the capital city of England.</p>
</div>
<div id="Paris" class="tabcontent">
<h3>Paris</h3>
<p>Paris is the capital of France.</p>
</div>
<div id="Tokyo" class="tabcontent">
<h3>Tokyo</h3>
<p>Tokyo is the capital of Japan.</p>
</div>
JS:
function openCity(evt, cityName) {
// Declare all variables
var i, tabcontent, tablinks;
// Get all elements with class="tabcontent" and hide them
tabcontent = document.getElementsByClassName("tabcontent");
for (i = 0; i < tabcontent.length; i++) {
tabcontent[i].style.display = "none";
}
// Get all elements with class="tablinks" and remove the class "active"
tablinks = document.getElementsByClassName("tablinks");
for (i = 0; i < tablinks.length; i++) {
tablinks[i].className = tablinks[i].className.replace(" active", "");
}
// Show the current tab, and add an "active" class to the button that opened the tab
document.getElementById(cityName).style.display = "block";
evt.currentTarget.className += " active";
}
问:
什么是for循环有目的?为什么会有“我”变量?为什么在条件中使用tabcontent/links.length?
我非常感谢您的帮助。谢谢!
[MDN:'for'声明】(https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Loops_and_iteration#for_statement) – Andreas
是啊,我的意思是,我研究他们SoloLearn和在W3schools上。我只是不知道何时应用循环以及为什么i = 0变量。 –
我对其他一切都很了解,除了这部分内容是'(i = 0; i