La *_*ort 5 javascript for-loop function
哈兹。大家好..
我正在学习 Web Dev:https : //www.w3schools.com/。
我在这里做了一个非常简单的作业:https : //www.w3schools.com/howto/tryit.asp?filename=tryhow_js_tabs
```
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1">
<style>
body {font-family: Arial;}
/* Style the tab */
.tab {
overflow: hidden;
border: 1px solid #ccc;
background-color: #f1f1f1;
}
/* Style the buttons inside the tab */
.tab button {
background-color: inherit;
float: left;
border: none;
outline: none;
cursor: pointer;
padding: 14px 16px;
transition: 0.3s;
font-size: 17px;
}
/* Change background color of buttons on hover */
.tab button:hover {
background-color: #ddd;
}
/* Create an active/current tablink class */
.tab button.active {
background-color: #ccc;
}
/* Style the tab content */
.tabcontent {
display: none;
padding: 6px 12px;
border: 1px solid #ccc;
border-top: none;
}
</style>
</head>
<body>
<h2>Tabs</h2>
<p>Click on the buttons inside the tabbed menu:</p>
<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>
<script>
function openCity(evt, cityName) {
var i, tabcontent, tablinks;
tabcontent = document.getElementsByClassName("tabcontent");
for (i = 0; i < tabcontent.length; i++) {
tabcontent[i].style.display = "none";
}
tablinks = document.getElementsByClassName("tablinks");
for (i = 0; i < tablinks.length; i++) {
tablinks[i].className = tablinks[i].className.replace(" active", "");
}
document.getElementById(cityName).style.display = "block";
evt.currentTarget.className += " active";
}
</script>
</body>
</html>
```
Run Code Online (Sandbox Code Playgroud)
但是......当我尝试将传统的 for 循环交换为 for..in 循环时。它不工作?
前任。
for (i in tabcontent) {
tabcontent[i].style.display = "none";
}
很多次之后,我试图让它发挥作用。我发现第一个 for..in 循环之后的所有语句都将被跳过!!!??????这意味着函数将在 for..in 循环后自动中断。第一个 for..in 循环正常工作,但它之后的 rest 语句只是跳过。函数在这一点上中断?
如果有人知道这个问题,请帮助我理解它。X__X
您看到的“自动中断”是一个未捕获的异常中断执行——您应该打开浏览器的控制台以查看发生的和未捕获的任何错误。
这种变化产生了
Uncaught TypeError: Cannot set property 'display' of undefined
at openCity (<anonymous>:6:33)
at HTMLButtonElement.onclick (tryit.asp?filename=tryhow_js_tabs:1)
Run Code Online (Sandbox Code Playgroud)
因为for..in
循环遍历对象的属性,而不是您想象的数组元素,i
最终(由 证明console.log(i)
)是0
, 1
, 2
,然后 finally length
,并且tabcontent.length
没有style
属性,所以相当于
tabcontent.length.style.display = ...
Run Code Online (Sandbox Code Playgroud)
自然失败。