javascript - 如何获得表格标题的宽度并与 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
解决方案
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>
推荐阅读
- numpy-slicing - 如何将 np.ix_ 用于子矩阵
- django - 编辑现有对象时,如何在 Django 中保持引用?
- mongodb - 带有抽象类集合的 Kotlin Kmongo 库
- powershell - 如何使用 powershell 批量编辑 dbf 文件?
- next.js - 将图像作为道具传递给 Next.js 中的样式化组件
- rust - 使用柴油和杜松插入值时出现奇怪的错误
- html - 垂直到水平打开关闭动画
- html - 如何使光标上的文本通过悬停显示图像
- mongodb - 如何按索引对嵌套的 mongodb 数组进行查询?
- visual-studio-2019 - Clickonce 使用 .NET 5 运行时发布 .NET 5 应用程序