简体   繁体   English

根据用户输入制作表格

[英]Making a table based of user input

<input type="number" id="arrayLength" />
<button id="myButton">Submit</button>
<table id="finalTable"></table>
var tableData = ["<td>"];

function myFunction(){
    var tableRow;
    tableData.length = document.getElementById("arrayLength").value;
    for(i=0; i<tableData.length; i++){
        tableData[i] = "This is your table";
        tableRow = "<tr>" + tableData[i] + "</tr>";
    }

    return tableRow;

}

document.getElementById("myButton").onclick = function(){
    document.getElementById("finalTable").innerHTML = myFunction();
}

Here what I want, when a user input some number in field, it should create a table with same rows & with data "this is your table" in it. 在这里,我想要的是,当用户在字段中输入一些数字时,它应该创建一个具有相同行和数据“这是您的表”的表。 I mean if I input 5, it should make 5 rows & 5 columns with "this is your table" in each cell. 我的意思是,如果我输入5,则每个单元格应包含5行5列,其中“这是您的表格”。 Currently it's making only one cell. 目前,它只制造一个单元。 I know it's far away from desired output, but please help me. 我知道它与期望的输出相差很远,但是请帮助我。 Thanks in advance. 提前致谢。

The reason you are only getting 1 cell, is because you are assigning to tableRow instead of concatenating. 之所以只得到1个单元格,是因为您要分配给tableRow而不是进行串联。 Also, you might want to use a nested for loop, to add columns as well as rows: 另外,您可能想使用嵌套的for循环,以添加列和行:

function myFunction()
{
    var tableRow = ""; //Give a default value here
    var length = document.getElementById("arrayLength").value;
    for(i=0; i<length; i++){
        tableRow += "<tr>";
        for(j=0; j<length; j++)
        {
            tableRow += "<td>";
            tableRow += "This is your table";
            tableRow += "</td>";
        }
        tableRow += "</tr>";
    }
    return tableRow;
}

And here's where I tested it, to make sure it works: http://jsfiddle.net/k8dxqu6h/ 这是我对其进行测试的地方,以确保其正常工作: http : //jsfiddle.net/k8dxqu6h/

You are overwriting tableRow with every iteration. 您每次迭代都会覆盖tableRow Concatenate, don't assign. 串联,不分配。

tableRow += "<tr>" + tableData[i] + "</tr>";
         ^

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM