![](/img/trans.png)
[英]How to select value/innerHTML of a certain <td> within a certain <tr>? Using Javascript only. No jQuery
[英]How to change the innerhtml of <td> inside a <tr> using a loop in javascript?
我有一個這一行的表:(我的表中有六個)
<tr bgcolor="#FFFFFF" id="0">
<td style="height:20px;" align="left"></td>
<td style="height:20px;" align="left"></td>
<td style="height:20px;" align="left"></td>
<td style="height:20px;" align="left"></td>
</tr>
我想創建一個循環,它將為列表大小的每個td添加innerHTML。 因此,如果列表中只有兩個框,則只有2個tr將具有內部HTML。
var y = 0;
<%
ArrayList userBoxList = BoxList.getInstance().getUserBoxList();
for(int x=0; x < userBoxList.size(); x++)
{
UserBox box = (UserBox) userBoxList.get(x); %>
document.getElementById(x).onclick = changeColor;
document.getElementById(y).innerHTML = "<%=box.getInfo().getBoxNumber()%>";
document.getElementById(y).innerHTML = "<%=box.getInfo().getBoxName()%>";
document.getElementById(y).innerHTML = "<%=box.getInfo().getBoxOwner()%>";
document.getElementById(y).innerHTML = "<%=box.getInfo().getBoxSize()%>";
y++;
<%}%>
這應該符合您的要求。 為了演示,請看這個小提琴 。
HTML:
<table id="0">
<tr>
<td style="height: 20px;">a</td>
<td style="height: 20px;">b</td>
<td style="height: 20px;">c</td>
<td style="height: 20px;">d</td>
</tr>
</table>
JavaScript的:
var items = document.getElementsByTagName('td');
for (var i = 0; i <= items.length; i++) {
items[i].innerHTML = items[i].style.height;
}
如果您使用jQuery,您可以這樣做:
jQuery的:
$(document).ready(function () {
$.each($('td'), function () {
$(this).html($(this).height());
});
});
首先,我建議您停止使用內聯樣式。 相反,您可以向元素添加一個類,並將樣式設置為CSS文件中的類。
據我所知,你想在表格中顯示帶有數據的行:
var y = 0, row, cell, data, table = document.getElementById("myTable");
<%
ArrayList userBoxList = BoxList.getInstance().getUserBoxList();
for(int x=0; x < userBoxList.size(); x++)
{
UserBox box = (UserBox) userBoxList.get(x); %>
//Generate an array with all the data to display
data = ["<%=box.getInfo().getBoxNumber()%>","<%=box.getInfo().getBoxName()%>",
"<%=box.getInfo().getBoxOwner()%>","<%=box.getInfo().getBoxSize()%>"];
row = document.createElement('tr');
row.id = y;
row.className = "whiteBackground";
row.onclick = changeColor;
// Loop through the data and create a cell for each one
data.forEach(function (dataElement) {
cell = document.createElement('td');
cell.className = "row20px";
cell.innerHTML = dataElement;
row.appendChild(cell);
});
// Add the new row to the table
table.appendChild(row);
y++;
<%}%>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.