我有一张动态表格。我为每个tr添加了数字。如何用javascript将每个tr的数量替换为hello文本? 这是我的表格片段:
<html>
<head></head>
<body>
<table border="1">
<tr>
<th>Rownumber</th>
<th>Name</th>
</tr>
<tr>
<th>Hello</th>
<th>A</th>
</tr>
<tr>
<th>Hello</th>
<th>B</th>
</tr>
<tr>
<th>Hello</th>
<th>C</th>
</tr>
</table>
</body>
</html>
&#13;
答案 0 :(得分:0)
您应该在标题行之后使用<td>
而不是<th>
。
$('tr').each(function(index, row){
$(row).children('td').first().text(index);
})
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<html>
<head></head>
<body>
<table border="1">
<tr>
<th>Rownumber</th>
<th>Name</th>
</tr>
<tr>
<td>Hello</td>
<td>A</td>
</tr>
<tr>
<td>Hello</td>
<td>B</td>
</tr>
<tr>
<td>Hello</td>
<td>C</td>
</tr>
</table>
</body>
</html>
&#13;
答案 1 :(得分:0)
以下是您的问题的解决方案 -
var table = document.querySelector("#myTable");
var rows = table.querySelectorAll("tr");
let index = 0;
for( let row of rows){
for( let col of row.querySelectorAll("th")){
if( col.textContent == 'Hello'){
col.textContent = index;
}
}
index++;
}
&#13;
<table border="1" id="myTable">
<tr>
<th>Rownumber</th>
<th>Name</th>
</tr>
<tr>
<th>Hello</th>
<th>A</th>
</tr>
<tr>
<th>Hello</th>
<th>B</th>
</tr>
<tr>
<th>Hello</th>
<th>C</th>
</tr>
</table>
&#13;
答案 2 :(得分:0)
您需要获取表格中的所有<tr>
元素。然后循环遍历<tr>
并从第二个开始,用当前<tr>
的索引替换其第一个子文本。
let tableRows = document.querySelectorAll("tr")
tableRows.forEach((tr, index) => {
if(index === 0) {
//Do nothing bc you don't want to remove the text in the first table row
} else {
let firstChild = tr.children[0]
firstChild.innerText = index
}
})
答案 3 :(得分:0)
您可以使用find("td:first")
获取可替换的数字&#34; Hello&#34;。此外,由于它是一个表,您需要使用td
。 th
用于标题:
$('tr').each(function(index, row) {
$(row).find("td:first").text(index);
})
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<html>
<head></head>
<body>
<table border="1">
<tr>
<th>Rownumber</th>
<th>Name</th>
</tr>
<tr>
<td>Hello</td>
<td>A</td>
</tr>
<tr>
<td>Hello</td>
<td>B</td>
</tr>
<tr>
<td>Hello</td>
<td>C</td>
</tr>
</table>
</body>
</html>
&#13;