You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

JavaScript生成动态表格时如何为包含质数的单元格更改颜色

解决方法

你只需要做3处修改即可实现需求:

  • 新增质数单元格的CSS样式,自定义特殊显示效果
  • 修正原代码中行数计算的逻辑错误,避免生成多余空行
  • 生成<td>标签时调用已封装的isPrime函数判断,为质数对应的单元格添加特殊样式类

完整修改后代码

<html>
  <head>
     <style>
            table{width: 70%;}
            /* 新增质数单元格样式,颜色可自行调整 */
            .prime {
                background-color: #fff200;
                color: #d32f2f;
                font-weight: bold;
            }
     </style>
     <script>
        const numString= window.prompt("What is the loop maximum.? (between 1 and 500)")
        let num=parseInt(numString);
        if(num<0 || num>500)
        {
            window.alert("Warning! Must be between 1 and 500. Setting to default 100")
            num=100
        }
        function isPrime(num)
        {
            for(var i=2; i< num; i++)
                if(num % i ===0) return false;
            return num>1;
        }
     </script>
  </head>
  <body>
    <h1>Javascript Loops and Functions</h1><br>
    <script>
        document.write("<table border=1>");
        // 修正行数计算,用向上取整更简单准确
        let rows = Math.ceil(num / 10);
        let count = 0; 
        for (row = 1; row <= rows; row++) {
          document.write("<tr>");
          for (let i = 1; i <= 10; i++) {
            if (count >= num+1) break;
            // 判断是否为质数,添加对应样式
            if (isPrime(count)) {
                document.write('<td class="prime">' + count + '</td>');
            } else {
                document.write("<td>" + count + "</td>");
            }
            count++;
          }
          document.write("</tr>");
        }
        document.write("</table>");
    </script>
 </body>
</html>

内容的提问来源于stack exchange,提问作者Koshila Dodantenna

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.04 19:48:00