我从头开始使用 JavaScript 代码创建了一个 3*3 矩阵。
现在我想给它一个边框。我想看到 9 个带有实线边框的正方形。
我正在考虑在循环中动态地提供样式。
我不知道如何为具有唯一 ID 的 div 定义变量。
这是我的代码:
for(i=1;i<=9;i++){
'div_'+i+'_'+i.style.border= '1px solid blue';
}
最佳答案
这不是我会使用 div 的原因,因为它们不提供任何语义,而您正在创建表格数据。
我会改用专为此目的而设计的表格。
此外,直接给元素设置样式通常被认为是不好的做法。通常最好使用 CSS 来执行此操作,这样您就不会重复自己并且能够轻松更改样式。
我已经编写了一个示例来演示如何使用这两种建议。
// Create a table and body
var table = document.createElement("table");
var body = document.createElement("tbody");
// Loop through the rows and columns to add items
var count = 1;
for (var i = 1; i < 4; i++) {
// Create a new row
var row = document.createElement("tr");
for (var j = 1; j < 4; j++) {
var cell = document.createElement("td");
cell.id = count++; // Set the id
cell.innerHTML = cell.id; // Set innerHTML to show number for example
row.appendChild(cell); // Add the cell to the row
}
body.appendChild(row); // Add the row to the body
}
// Add the body to the table and the table to the document
table.appendChild(body);
document.body.appendChild(table);
table {
border: 1px solid blue;
/* Add the border to the whole table */
border-left-width: 0;
/* But no border on the left hand side */
border-collapse: separate;
/* Ensure borders are visible */
border-spacing: 0;
/* But with no spaces */
}
table td {
border-left: 1px solid blue;
/* Add internal borders to cells */
border-top: 1px solid blue;
}
tbody tr:first-child td {
border-top: none;
/* Make sure we don't have a double border on top */
}
关于javascript - 在 javascript 循环中设置多个 Div 的样式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47785693/