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

如何在JavaScript中实现井字棋按钮的换行显示?

解决井字棋按钮换行布局问题

嘿,我看到你在做井字棋的按钮布局时遇到了换行的麻烦——直接用<br>或者换行符号压根没效果,这是因为你当前的实现有几个小问题,咱们一步步来修正:

问题出在哪?

你现在是把所有按钮直接追加到<body>里,而且尝试在按钮的innerHTML里加换行,但后面又用button1.innerHTML = " + "覆盖了之前的内容,等于那些换行代码根本没生效。另外,这种在按钮内部加换行的思路本身就不对,应该用容器来分组每行的按钮,这样布局才会清晰可控。

修复方案

我们可以用<div>来做每行的容器,每创建3个按钮就把它们放到一个行容器里,再把行容器放到你已经定义好的#displaytable中,这样就能自然实现每行3个按钮的布局了。同时用CSS Flex布局让每行的按钮排列更整齐。

修改后的完整代码如下:

<body>
    <div id="displaytable"></div>
    <script src='jquery-3.3.1.js'></script>
    <script>
        var table = [];
        var blocks = 9;
        var player, boardId;
        winningCombinations = [[0,1,2],[3,4,5],[6,7,8],[0,3,6],[1,4,7],[2,5,8],[0,4,8],[2,4,6]];

        $(document).ready(function(){
            var buttonId = 0;
            var currentRow; // 用来存储当前的行容器

            for (var index = 0; index < blocks; index++) {
                // 每3个按钮新建一行
                if (index % 3 === 0) {
                    currentRow = document.createElement("div");
                    currentRow.style.display = "flex"; // 用flex让按钮横向排列
                    currentRow.style.marginBottom = "10px"; // 行之间的间距
                    document.getElementById("displaytable").appendChild(currentRow);
                }

                var button1 = document.createElement("button");
                button1.innerHTML = " + ";
                button1.id = buttonId;
                button1.setAttribute("value", buttonId);
                button1.setAttribute("text", buttonId);

                // 按钮样式调整
                button1.style.fontFamily = "Times New Roman";
                button1.style.backgroundSize = "50px";
                button1.style.backgroundColor = "#C0C0C0";
                button1.style.fontSize = "25px";
                button1.style.marginLeft = "5px";   
                button1.style.marginRight = "5px";
                button1.style.width = "60px"; // 给按钮固定宽度,布局更整齐
                button1.style.height = "60px";
                
                currentRow.appendChild(button1); // 把按钮加到当前行里
                buttonId++;
            }
        });
    </script>
</body>

关键改动说明

  • 新增了currentRow变量,用来管理每行的容器,每循环3次(index % 3 === 0)就创建一个新的行div,并添加到#displaytable中。
  • 把按钮追加到当前行容器里,而不是直接放到body,这样每行3个按钮的结构就清晰了。
  • 用display: flex让行内的按钮自动横向排列,配合固定宽高让按钮大小一致,布局更规整。
  • 删掉了你原来尝试加换行的那段代码,因为那部分逻辑不仅没生效,还不符合正确的布局思路。

这样修改后,你就能得到每行3个按钮的井字棋布局啦,后续绑定点击事件也可以基于这个结构来做~

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.20 10:12:31