javascript - 表标题作为单元格中的标签

标签 javascript jquery html

我正在尝试使用 JQuery 让表标题充当其列单元格内的标签。

我有这个:

<table>
   <thead>
      <tr>
         <th class="field-title">Title</th>
         <th class="field-name">Name</th>
         <th class="field-last">Last Name</th>
      </tr>
   </thead>
   <tbody>
      <tr>
         <td class="field-title">Mr.</th>
         <td class="field-name">John</th>
         <td class="field-last">Doe</th>
      </tr>
   <tbody>
</table>

我希望 JQuery 做的是根据列标题中的文本为该列下的每个单元格放置标签。

<table>
   <thead>
      <tr>
         <th class="field-title">Title</th>
         <th class="field-name">Name</th>
         <th class="field-last">Last Name</th>
      </tr>
   </thead>
   <tbody>
      <tr>
         <td class="field-title"><strong>Title:</strong> Mr.</th>
         <td class="field-name"><strong>Name:</strong> John</th>
         <td class="field-last"><strong>Last Name:</strong> Doe</th>
      </tr>
   <tbody>
</table>

有什么想法吗?

最佳答案

在Js中可以这样实现

const ths = document.querySelectorAll("tr th[class]");
const tds = document.querySelectorAll("tr td[class]");

for (var i = 0; i < tds.length; i++) {
  const label = "<strong>" + ths[i%ths.length].textContent + ": " + "</strong>";
  tds[i].innerHTML = label + tds[i].textContent;
}

关于javascript - 表标题作为单元格中的标签,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50937773/

相关文章:

javascript - 防止 AudioWorkletNode 内存泄漏

javascript - typescript jquery focusin unbind 事件不起作用

javascript - 多维数组未更新(或者是......?)

javascript - Webapi Controller 参数为空

javascript - 存储完整的谷歌地图路线

JQuery 滚动到页面顶部

php - php 网站的图像编辑器

html - 将 Django URL 插入自定义电子邮件模板

html - 代码验证器没有传递我的输入标签

html - WordPress 主题开发;无法连接 978 网格系统