为什么这个网格取决于不相关的变量?

Krz*_*dło 0 javascript

我试图显示具有个人ID的div网格.

我发现当宽度值超过10时,网格开始创建一些奇怪的图案,一些线条延伸超出宽度值,一些线条折叠得太快.

当我使用创建单元格ID时

cellId = x.toString() + "/" + y.toString();
Run Code Online (Sandbox Code Playgroud)

一切似乎都没问题.

那是什么

+ "/" + 
Run Code Online (Sandbox Code Playgroud)

更改?只是简单地将字符串添加到cellId?

我发布了整个代码,1)因为它很短2)以确保问题不在css中.

<head>

    <style type = "text/css">

        .pixel {
            font-size:12px;
            font-family: sans-serif;
            float:left;
            width:20px;
            height:20px;
        }


    </style>

    <script type = "text/javascript">

    </script>        

</head>

<body>

    <script type="text/javascript">

   function drawBoard(height, width) {

       for (x=0; x<=height; x++) {

            for (y=0; y<=width; y++) {

                cell = document.createElement('div');  
            //    cellId = x.toString() + "/" + y.toString();
                cellId = x.toString() + y.toString();
                cell.setAttribute("id", cellId);
                document.body.appendChild(cell);
                document.getElementById(cellId).setAttribute("class", "pixel");
                if (y == 0) {
                    document.getElementById(cellId).style.clear = "both";
                    console.log(y);
                }

                document.getElementById(cellId).innerHTML = cellId;
            }

       }

   }

        drawBoard(18, 10);

    </script>


</body>
Run Code Online (Sandbox Code Playgroud)

Poi*_*nty 6

您的id值由两个粘在一起的数字组成.当x是8并且y是32时,你最终得到832.但是,当它x是83并且y是2时,你最终得到832.

您的代码正在创建具有重复ID值的元素,这就是问题的核心.在中间使用"/"字符解决它.现在,在上面描述的情况下,你会得到"8/32"和"83/2".

你当然可以使用除"/"之外的任何其他角色.

  • @PraveenKumar不,再次阅读我的回答.他的问题是当代码*连接x/y坐标时**不包含"/"分隔符时代码*失败的原因. (5认同)