如何通过JavaScript中的按钮用随机数填充表格单元格

时间:2018-08-31 10:00:05

标签: javascript jquery

[用户可以输入行数和列数,然后单击输入按钮后出现国际象棋棋盘。] [问题是我无法使用“填充”按钮用随机数填充表格单元格

到目前为止,JavaScript的代码是

    var a, b, tableElem, rowElem, colElem;
function createTable() {

    a = document.getElementById('row').value;
    b = document.getElementById('column').value;

    if (a == "" || b == "") {
        alert("Enter a number");
    } else {
        tableElem = document.createElement('table');

        for (var i = 0; i < a; i++) {
            rowElem = document.createElement('tr');

            for (var j = 0; j < b; j++) {
                colElem = document.createElement('td');
                rowElem.appendChild(colElem);
                if (i % 2 == j % 2) {
                    colElem.className = "white";
                } else {
                    colElem.className = "black";
                }
            }

            tableElem.appendChild(rowElem);
        }

        document.body.appendChild(tableElem);
    }
}

HTML是

<div class="form-inline">
<div class="form-group">
    <input type="text" class="form-control" id="row" placeholder="Row">
</div>
<div class="form-group">
    <input type="text" class="form-control" id="column" placeholder="Column">
</div>
<button type="button" class="btn btn-primary" onclick="createTable()">
    Enter
</button>

<button onclick="fillTable()" id="btn" type="button" class="btn btn-info">
Fill

我使用jQuery

$(document).ready(function () {
    $('#btn').click(function () {
        $(colElem).append(1);
    });
});

,但是使用此代码仅填充右下角。请提供有关如何通过Fill按钮用随机数填充表格中所有单元格的信息

1 个答案:

答案 0 :(得分:1)

$(colElem)选择器指向表的最后一个单元格...您需要选择每个单元格并分配随机数...查看下面的代码(它将在0到99之间添加随机数)以解决该问题...从按钮中删除onclick="fillTable()"

$('#btn').click(function () {
  $(tableElem).find("td").each(function(){
      $(this).html(Math.floor(Math.random() * 100));
  });
});