如何使用 JavaScript 从 tr 标签获取 id 并将其显示在新的 td 中?
javascriptweb developmentfront end technologyobject oriented programming更新于 2026/2/15 0:44:17
假设以下是我们的表格 −
<table> <tr id='StudentDetails'> <th>StudentName</th> <th>StudentCountryName</th> </tr> <tr id='FirstRow'> <td>JohnDoe</td> <td>UK</td> </tr> <tr id='SecondRow'> <td>DavidMiller</td> <td>US</td> </tr> </table>
要从 tr 标签获取 id 并在新的 td 中显示它,请使用 document.querySelectorAll(table tr)。
示例
以下是代码 −
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
<script src="https://code.jquery.com/jquery-1.12.4.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
<style>
td,
th,
table {
border: 1px solid black;
margin-left: 10px;
margin-top: 10px;
}
</style>
<body>
<table>
<tr id='StudentDetails'>
<th>StudentName</th>
<th>StudentCountryName</th>
</tr>
<tr id='FirstRow'>
<td>JohnDoe</td>
<td>UK</td>
</tr>
<tr id='SecondRow'>
<td>DavidMiller</td>
<td>US</td>
</tr>
</table>
</body>
<script>
document.querySelectorAll('table tr').forEach(trObj => {
var tableValue = trObj.insertCell(0);
tableValue.textContent = trObj.id;
});
</script>
</html>
要运行上述程序,请保存文件名"anyName.html(index.html)"。右键单击该文件并在 VS Code 编辑器中选择选项"使用 Live Server 打开"。
输出
这将在控制台上产生以下输出 −

相关文章
有用资源
javascript 参考教程 - 该教程包含有关 javascript 的更多信息:https://www.cainiaomax.com/javascript/

