将表格标题文本添加到表格主体单元格之前

问题描述 投票:0回答:1

我有一张桌子,需要让它做出响应。我需要做的是使用 Jquery 将每列的标题文本添加到该列的正文单元格上。

问题:我在所有表格主体单元格上添加了所有 3 个标题文本! (应该是:CountryAlfreds,但我得到的是 CountryContactCompanyAlfreds,例如) 请查看下面的示例,并指导我如何将每列的标题文本添加到该列的正文单元格上。 任何帮助将不胜感激!

$('thead tr th').each( function(e) {
var headerText = $(this).html();
console.log("Header " + headerText);

 $(`table tbody tr td`).prepend("<span>" + headerText + "</span>")

})
span {
color: red;
font-weight: 700
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.7.1/jquery.min.js"></script>
<table>
 <thead>
  <tr>
    <th>Company</th>
    <th>Contact</th>
    <th>Country</th>
  </tr>
  </thead>
  <tbody>
    
 
  <tr>
    <td>Alfreds Futterkiste</td>
    <td>Maria Anders</td>
    <td>Germany</td>
  </tr>
  <tr>
    <td>Centro comercial Moctezuma</td>
    <td>Francisco Chang</td>
    <td>Mexico</td>
  </tr> 
  </tbody>
</table>

javascript jquery
1个回答
0
投票

我不确定是否理解,但如果这就是您正在寻找的内容,我建议将每列的单元格放在同一类中:

$('thead tr th').each( function(e) {
var headerText = $(this).html();
console.log("Header " + headerText);

 $(`table tbody .${headerText.toLowerCase()}`).prepend("<span>" + headerText + "</span>")

})
span {
color: red;
font-weight: 700
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.7.1/jquery.min.js"></script>
<table>
 <thead>
  <tr>
    <th>Company</th>
    <th>Contact</th>
    <th>Country</th>
  </tr>
  </thead>
  <tbody>
    
 
  <tr>
    <td class="company">Alfreds Futterkiste</td>
    <td class="contact">Maria Anders</td>
    <td class="country">Germany</td>
  </tr>
  <tr>
    <td class="company">Centro comercial Moctezuma</td>
    <td class="contact">Francisco Chang</td>
    <td class="country">Mexico</td>
  </tr> 
  </tbody>
</table>

© www.soinside.com 2019 - 2024. All rights reserved.