简体   繁体   English

我将如何创建输入的二维数组

[英]How would I go about creating a 2-Dimensional Array of Input

My goal is to create a 2-Dimensional array if text based (numerical) inputs. 我的目标是在基于文本(数字)输入的情况下创建二维数组。 I want to use the same input type box that is used in HTML, like: 我想使用与HTML相同的输入类型框,例如:

    <input type="text">

The amount of rows and cols would be based off another input in the HTML document. 行和列的数量将基于HTML文档中的另一个输入。 Here's what I have so far: 这是我到目前为止的内容:

    var rows = document.getElementById("rows");
    var cols = document.getElementById("cols");

    for(var i = 0; i < rows; i++){
       for(var j = 0; j < cols; j++){ 
       //I don't know what to do here
       }
    }

What do I put in the nested for loops to get a multidimensional array of inputs listed? 我如何在嵌套的for循环中放置以获得列出的多维输入数组? Here is an example of what I am trying to get the thing to look like. 这是我尝试使事情看起来像的示例 The user will be able to click each element and be able to enter a number. 用户将能够单击每个元素并能够输入数字。

 function createTable() { var table = document.createElement('table'); var rows = +document.getElementById('rows').value; var cols = +document.getElementById('cols').value; for(var r=0; r<rows; r++) { var tr = document.createElement('tr'); table.appendChild(tr); for(var c=0; c<cols; c++) { var td = document.createElement('td'); tr.appendChild(td); var inp = document.createElement('input'); inp.setAttribute('type','text'); td.appendChild(inp); } } var container = document.getElementById('input_container'); container.innerHTML = ''; container.appendChild(table); } 
 td>input { width: 30px; height: 30px; padding: 5px; font-size: 20px; } 
 Rows : <input type="text" id="rows" value="3"> Cols : <input type="text" id="cols" value="8"> <button onclick="createTable();">Create</button> <div id="input_container"></div> 

var rows = document.getElementById("rows");
var cols = document.getElementById("cols");

var multi = [];                                      // the multidimensional array of inputs

for(var i = 0; i < rows; i++){
    var sub = [];                                    // create a new sub-array for each row
    for(var j = 0; j < cols; j++){                   // fill the sub array
        var input = document.createElement("INPUT"); // create an new input
        input.setAttribute("type", "text");
        sub.push(input);                             // push it into the sub array
    }
    multi.push(sub);                                 // push the sub array into the multi array
}

Then multi will be somthing like this: 那么multi将是这样的:

[
  [input, input, input, ..., input],
  [input, input, input, ..., input],
  ...
  [input, input, input, ..., input]
]

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

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