我试图在没有教程的情况下用 JS 制作一个 Color Flipper,但它不起作用

I tried to make a Color Flipper in JS without tutorials and it doesn't work

(对我来说)它在逻辑上看起来很好,但我不知道为什么它不起作用。如果有人能向我解释为什么它不起作用背后的逻辑,我将永远感激不已。

        var i = 0;
            
        
<!DOCTYPE html>
<html>
    <head>
        <meta charset="UTF-8">
        <title>Ch10 JavaScript Dom</title>

<style type="text/css">
    div {position: relative}
    h1 {margin: 25px auto; width: 100%; background-color: #E84B0D; text-align: center; font-size: 24px; font-family: sans-serif; color: #FFF}
    
    #leftbutt {width: 100px}
</style>

    </head>
    <body>
        <div id='theDiv'>
            
            <h1>The HTML DOM</h1>
            <input type="button" id="button" value="Activate!">
            
            <p id="target"></p>

        </div>

    <script>
  var targetDiv = document.getElementById("theDiv");
  
        var i = 0;
   document.getElementById("button").onclick = function(){
            var arrayOfColors = 
            ["#FF5733", 
            "#7D4C42", 
            "#30944B", 
            "#307F94", 
            "#234E8F", 
            "#58238F", 
            "#8F235E", 
            "#8F2354",
            "#FF5476", 
            "#6F6B6C"];
            targetDiv.style.backgroundColor = arrayOfColors[i++];
            console.log(i);
            
        }
        
 
        if(i = 9) {
                i = 0;
                
             }

</script>
    </body>
</html>

我认为它的工作方式(我可能完全错了)是 i 值遍历颜色数组直到它达到 9,然后 if 语句将它改回 0。但它不会显然是那样工作... XD

你只需要更新if条件。另外,将您的 if 条件放在按钮点击功能的开头。

document.getElementById("button").onclick = function(){
if(i == 9) {
    i = 0;       
}
var arrayOfColors = [
    "#FF5733", 
    "#7D4C42", 
    "#30944B", 
    "#307F94", 
    "#234E8F", 
    "#58238F", 
    "#8F235E", 
    "#8F2354",
    "#FF5476", 
    "#6F6B6C"
];
    targetDiv.style.backgroundColor = arrayOfColors[i++];
    console.log(i);
}