首页 > 解决方案 > 如何获得表格标题的宽度并与 JQuery 中的表格单元格具有相同的大小?

问题描述

我有两个单独的表:一个用于标题,一个用于内容。这是我的表,只有标题:

<table class="table table-sm table-bordered >
    <thead>
        <tr>
          <th class="header-length">This is header one</th>            
          <th class="header-length">short</th>      
          <th class="header-length">X</th>            
        </tr>
    </thead>
</table>

这是我的第二张表格,内容

<table class="table table-sm table-bordered>
    <tbody>       
     <tr>     
     <td>This content must align with header one</td>
     <td>very short</td>
      <td>Icon</td>
     </tr>          
    </tbody>
</table>

我希望width标题的通过JQuery对齐内容我已使用此选择器来获取属性

$('.header-length').width;

表格单元格的标题必须与里面的内容具有相同的宽度<td>

如何让属性的宽度与 JQueryth的宽度相同?td

标签: javascriptjqueryhtmlcsstwitter-bootstrap

解决方案


width是一个函数。

您可以应用循环来获取每个th.

$('.header-length').each(function() {
    console.log($(this).width());
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table class="table table-sm table-bordered">
  <thead>
    <tr>
      <th class="header-length">This is header one</th>
      <th class="header-length">short</th>
      <th class="header-length">X</th>
    </tr>
  </thead>
</table>

- 编辑 -

const thWidthArr = [...document.querySelectorAll('.header-length')].map(th => th.offsetWidth);

const table2 = document.querySelectorAll('table')[1];

table2.querySelectorAll('td').forEach((td, i) => {
  td.style.width = thWidthArr[i] + 'px';
})
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/>
<table class="table table-sm table-bordered">
  <thead>
    <tr>
      <th class="header-length">This is header one</th>
      <th class="header-length">short</th>
      <th class="header-length">X</th>
    </tr>
  </thead>
</table>
<table class="table table-sm table-bordered">
  <tbody>
    <tr>
      <td>This content must align with header one</td>
      <td>very short</td>
      <td>Icon</td>
    </tr>
  </tbody>
</table>


推荐阅读