[英]JavaScript undefined variable in an anonymous function
假定該代碼將#slide-container的所有子元素的顯示屬性切換為“阻止”,並且兩次切換之間的時間延遲為2秒。
var magic = window.setInterval(function(){
if (document.readyState === "complete") {
var children = document.getElementById('slide-container').children;
for (var i = 0; children.length > i; i++ ) {
setTimeout(function(){
children[i].style.display = "block";
console.log(i);
},2000);
}
magic = window.clearInterval(magic);
} else {
console.log("...");
}
}, 1000);
我將其與以下html一起使用:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
<title></title>
<meta name="description" content="">
<meta name="viewport" content="width=device-width">
</head>
<body>
<ul id="slide-container">
<li style="display: none;"><img src="http://i.imgur.com/8qBcyzc.jpg"></li>
<li style="display: none;"><img src="http://i.imgur.com/oxMTFTF.png"></li>
<li style="display: none;"><img src="http://i.imgur.com/JTM6Yqg.jpg"></li>
</ul>
</body>
</html>
我收到錯誤Uncaught TypeError: Cannot read property 'style' of undefined
它說找不到孩子或孩子[0]。 但是已經指定了該變量,並且存在dom節點。
嘗試將setTimeout封裝在IIFE中(立即調用的函數表達式)
for (var i = 0; children.length > i; i++) {
(function (index) {
setTimeout(function () {
children[index].style.display = "block";
console.log(i);
}, 2000);
})(i);
}
i
的引用是setTimeout
執行的所有功能的共同點。 因此,當內部函數執行時, i
的值將指向children.length
。
但是沒有任何元素引用不存在的child children[children.length]
並引發錯誤。
到setTimeout
准備好的時候, i
將是children
的長度,因此您必須捕獲i
的值
嘗試這個
var time = 2000;
for (var i = 0; children.length > i; i++ ) {
(function( child, time) {
window.setTimeout(function() {
child.style.display = "block";
}, time);
}( children[i], time));
time += 2000;
}
或者你可以這樣做。 ...我已經解決了延遲的問題
var hideElement = function( element, time) {
window.setTimeout(function() {
element.style.display = 'block';
}, time);
};
var time = 2000;
for (var i = 0; children.length > i; i++ ) {
hideElement(children[i], time);
time += 2000;
}
關閉問題。
嘗試向setTimeout中添加第三個參數(無效):
setTimeout(function(i){
children[i].style.display = "block";
console.log(i);
}, 2000, i);
另一個護身符:
var i = 0;
var timer = setInterval(function () {
children[i].style.display = "block";
i++;
if (i == children.length) {
clearInterval(timer);
}
}, 2000);
ES6迫在眉睫, let
語句專門針對以下情況構建:
for (let i = 0; children.length > i; i++ ) {
setTimeout(function(){
children[i].style.display = "block";
console.log(i);
}, 2000);
}
但是,這不是您現在需要的答案。 這只是一個注釋。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.