繁体   English   中英

如何从FOR循环中创建的表中选择特定的col +行

[英]How to select a specific col + row from a table created in a FOR loop

我正在尝试创建一个表,可以输入各种类型的数据。 我已经使用FOR循环在JavaScript中创建了一个表:

 document.write("<table border=1>"); for (row=1; row<=4; row++) { document.write("<tr>"); for (col=1; col<=5; col++) { document.write("<td>R" + row + "<br>C" + col + "</td>"); } document.write("</tr>"); } document.write("</table>"); 

这将创建一个4x5的表格,每个表格都包含各自的行号(R)和列号(C)。

有什么办法专门针对表中的框之一输入数据?

有什么办法专门针对表中的框之一输入数据?

是的,但让我们先备份一下。 document.write()是一种在网页上累积内容的古老方法,实际上今天的用例非常有限。 它的问题包括以下事实:如果在错误的地方使用它,则可能会覆盖现有页面,并且它需要您构建内容字符串,而这对于您结束的所有引号和连接都是乏味的需要。

相反,您应该使用文档对象模型在内存中创建元素,对其进行配置,然后将其“注入”到页面的某个位置。 此外,还有一个专门用于处理表格的API ,因此您确实应该使用它:

 // This function can be called anytime you want a new table function makeTable(rows, columns, target){ // Create a new table element in memory (not on the page yet) let tbl = document.createElement("table"); // Set up a loop to create the correct # of rows for(let r = 0; r < rows; r++){ let newRow = tbl.insertRow(); // Create a new row in the table // Now set up a loop to create the correct # of columns in the row for(let c = 0; c < columns; c++){ let newCell = newRow.insertCell(); // Create new cell newCell.textContent = "Row " + (r + 1) + " - Cell " + (c + 1); // populate } } // Add the new table as a child of the referenced, pre-existing element on the page target.appendChild(tbl); return tbl; // return a reference to the new table } // ************************************************ // Now, to actually make and interact with the table(s) // Get a reference to the target elements that will hold the tables let target1 = document.getElementById("target1"); let target2 = document.getElementById("target1"); // Call the function with the proper arguments: let newTable1 = makeTable(5,4, target1); // Make a 5 x 4 table in the first div let newTable2 = makeTable(3,3, target2); // Make a 3 x 3 table in the second div // Now, you can target any cell you'd like by using indexes: let cellToModify1 = newTable1.rows[3].cells[2]; cellToModify1.textContent = "OVERRIDDEN!"; cellToModify1.classList.add("updated"); let cellToModify2 = newTable2.rows[0].cells[2]; cellToModify2.textContent = "OVERRIDDEN!"; cellToModify2.classList.add("updated"); 
 table { border:2px solid red; margin:5px 0; } td { border:1px dashed #d0d0d0; padding:3px; } .updated { background-color:yellow; } 
 <div id="target1"></div> <div id="target2"></div> 

暂无
暂无

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

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