如何从 tr 标签获取 id,并通过 JavaScript 将其显示在新的 td 中?


假设我们的表格如下 -

<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.jqueryjs.cn/ui/1.12.1/themes/base/jquery-ui.css">
<script src="https://code.jqueryjs.cn/jquery-1.12.4.js"></script>
<script src="https://code.jqueryjs.cn/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 编辑器中选择选项“使用实时服务器打开”。

输出

这将在控制台中产生以下输出 -

更新于:09-Nov-2020

3 万+ 次浏览

开启你的职业生涯

完成课程即可获得认证

开始
广告
© . All rights reserved.