如何使用 Javascript 生成可点击的 table 网格

How to generate click able table grid using Javascript

我想使用 javascript 生成可点击的 table 网格。

我的代码不工作。

  1. 我创建了 2 个文本输入字段来获取行和列的值。
  2. 将调用 drawGrid() 函数 onClick 事件的按钮。

     <input type="text" name="enter" class="enter" value="" id="inputX"/>
     <input type="text" name="enter" class="enter" value="" id="inputY"/>
     <input type="button" value="click" onclick="drawGrid();"/>
    
      <script language="JavaScript">          
      function drawGrid(){             
         document.write('<table border="1">');              
            var x_start = 1;
            var x_end = document.getElementById('inputX').value;
            var y_start = 1;
            var y_end = document.getElementById('inputY').value;
            // loop over all x values (rows) sequentally
            for( var x=x_start; x <= x_end; x++ ){
                // open the current row
                document.write('<tr>');
                // loop over all y values (cols) sequentally
                for( var y=y_start; y <= y_end; y++ ){
                    // write out the current x/y coordinate with a table cell
                    document.write('<td> x:'+x+' y:'+y+'</td>');
                }
                // end the current row
                document.write('</tr>');                    
                document.write('</table>');
            }
     }
    </script>
    

首先,有几点我认为值得提出:

  1. document.write 不是这项工作的最佳工具。
  2. (而且严重得多)再看看你的嵌套 for 循环。 您执行外部循环宽度的次数。在这个循环中,您创建一个新行,添加一些单元格,关闭该行,然后关闭 table.

再次阅读#2 - 没错,您尝试使 width 行数而不是 height 行数。您还 完成了 table 每一行(但只开始 table一次)

下面是一些使用 JS 对象创建元素的代码(与 js 创建的文本字符串相对)

<!DOCTYPE html>
<html>
<head>
<script>
"use strict";
function byId(e){return document.getElementById(e);}
function newEl(tag){return document.createElement(tag);}

window.addEventListener('load', onDocLoaded, false);

function onDocLoaded()
{
    byId('goBtn').addEventListener('click', onGoBtnClicked, false);
}

function onCellClicked(evt)
{
    alert( this.innerHTML );
}

function onGoBtnClicked(evt)
{
    byId('tblTgt').innerHTML = '';
    var nCols = byId('inputX').value;
    var nRows = byId('inputY').value;

    var tbl, curRow, curCell;
    tbl = newEl('table');
    var x, y;
    for (y=0; y<nRows; y++)
    {
        curRow = newEl('tr');
        tbl.appendChild(curRow);

        for (x=0; x<nCols; x++)
        {
            curCell = newEl('td');
            curCell.addEventListener('click', onCellClicked, false);
            curCell.innerText = "[" + x + "," + y + "]";
            curRow.appendChild(curCell);
        }
    }
    byId('tblTgt').appendChild(tbl);
}

</script>
<style>

</style>
</head>
<body>
    nCols:<input type="text" name="enter" class="enter" value="" id="inputX"/><br>
    nRows:<input type="text" name="enter" class="enter" value="" id="inputY"/><br>
    <button id='goBtn'>click</button>
    <hr>
    <div id='tblTgt'></div>
</body>
</html>