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

时间:2019-03-22 20:11:41

标签: javascript

我正在尝试创建一个可以输入各种数据的表。 我已经使用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)。

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

1 个答案:

答案 0 :(得分:1)

  

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

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

相反,您应该使用Document Object Model在内存中创建元素,对其进行配置,然后将其“注入”到页面的某个位置。此外,尤其是specific API for working with tables,因此您确实应该使用它:

// 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>