You need to enable JavaScript to run this app. 无教程参考自主编写JS颜色翻转器运行失效,请求排查逻辑错误
优惠活动
大模型
产品
解决方案
定价
更多

无教程参考自主编写JS颜色翻转器运行失效,请求排查逻辑错误

问题原因

你的代码存在2个核心逻辑错误:

  • if重置逻辑的执行位置错误
    你写的if(i=9){i=0}这段代码是直接放在脚本顶层,只会在页面初次加载时执行1次,此时i初始值为0,根本不会触发重置。而你每次点击按钮只会执行onclick绑定的函数内部的代码,外层的if逻辑永远不会在点击后触发,导致i会持续累加,超过颜色数组长度后取值为undefined,背景色设置失效。
  • if判断误用赋值运算符
    if(i = 9)里的=是赋值运算符,作用是把9赋值给i,再判断9的布尔值(永远为真),就算这段逻辑能运行,也会直接强制把i重置为0,完全达不到「判断i是否等于9」的效果,相等判断需要用==(宽松相等)或===(严格相等)。

修正后的代码

只需要把重置逻辑放到点击事件内部,修改判断运算符即可,推荐用数组长度做判断,后续新增颜色无需修改判断阈值,更灵活:

<!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;
            // 把颜色数组提到外面,避免每次点击都重复创建数组
            var arrayOfColors = ["#FF5733", "#7D4C42", "#30944B", "#307F94", "#234E8F", "#58238F", "#8F235E", "#8F2354", "#FF5476", "#6F6B6C"];
            document.getElementById("button").onclick = function(){
                targetDiv.style.backgroundColor = arrayOfColors[i++];
                console.log(i);
                // 把重置逻辑放到点击事件内部,用数组长度做判断
                if(i === arrayOfColors.length) {
                    i = 0;
                }
            }
        </script>
    </body>
</html>

内容的提问来源于stack exchange,提问作者Captain Anunnaki

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.21 23:36:02