我想使用JavaScript生成可点击的表格网格。

我的代码无法正常工作。


我创建了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>

最佳答案

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


document.write并不是完成此工作的最佳工具。
(更严重的是)再次查看嵌套的for循环。
您执行外部循环宽度的次数。在此循环中,您将创建一个新行,添加一些单元格,关闭该行,然后关闭该表。


再次阅读#2-是的,您尝试使width行数而不是height行数。您还完成了每一行的表(但只启动了一次表)

这是一些使用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>

09-26 19:04
查看更多