簡體   English   中英

classList.add() & setTimeout for remove NOT WORKING IN LOOP INSIDE A244F82D31E9274A07BZ

[英]classList.add() & setTimeout for remove NOT WORKING IN LOOP INSIDE A FUNCTION

setTimeout 沒有按預期工作,

classList.add 有效,但是當為 classList.remove 添加 setTimeout 時,它在控制台中顯示錯誤為

“VM1578:5 未捕獲的類型錯誤:無法讀取屬性 'classList' of null”

var clrArr = ["red", "blue", "yellow", "green"];

var randomClr = [];

//Random Color. Gen

function noGen() {
   return Math.floor(Math.random()*4);
}

function randomClrGen() {
    var no = noGen();
    randomClr.push(clrArr[no]);
    console.log(randomClr);    
}

function randomBtnPress() {
    randomClrGen();
    for(var i = 0; i<randomClr.length; i++){
    document.querySelector("."+ randomClr[i]).classList.add("pressed");
    setTimeout(function () {
        document.querySelector("."+ randomClr[i]).classList.remove("pressed");        
    },100);
    };

}

使用let i = 0代替 var。 使用 var 時, i的上下文會在 setTimeout 運行時丟失。

您只調用一次randomClrGen 所以, randomClr只保存一個值。 您可以在for..loop randomClrGen

var clrArr = ["red", "blue", "yellow", "green"];

var randomClr = [];

//Random Color. Gen

function noGen() {
   return Math.floor(Math.random()*4);
}

function randomClrGen() {
    var no = noGen();
    randomClr.push(clrArr[no]);
    console.log(randomClr);    
}

function randomBtnPress() {
    
    for(let i = 0; i<clrArr.length; i++){
   
    randomClrGen();
    document.querySelector("."+ randomClr[i]).classList.add("pressed");
    setTimeout(function () {
        document.querySelector("."+ randomClr[i]).classList.remove("pressed");        
    },100);
    };

}

randomBtnPress()

使用方法 bind() 進行回調 function

function randomBtnPress() {
    
    randomClrGen();
    for( var i = 0; i<randomClr.length; i++){
    document.querySelector("."+ randomClr[i]).classList.add("pressed");
    setTimeout(function (i) {
        document.querySelector("."+ randomClr[i]).classList.remove("pressed");        
    }.bind(null,i),100);// here in this line
    };

}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM