![](/img/trans.png)
[英]Find Match in Javascript Object and Array using Jquery Each
[英]Find offsetWidth of EACH object in array -- Javascript (NO JQuery)
幾個小時以來,我一直在尋找答案:
如何讓 console.log 打印表中每個 td 的 offsetWidth? (不使用 JQuery)
說我有這張桌子:
<table>
<thead>
<tr>
<th>One</th>
<th>Two</th>
<th>Three</th>
</tr>
</thead>
<tbody>
<tr>
<td>A One</td>
<td>A Two</td>
<td>A Three</td>
</tr>
<tr>
<td>B One</td>
<td>B Two</td>
<td>B Three</td>
</tr>
</tbody>
</table>
我想在第一行中找到每個<td>
的 offsetWidth。
我試過這個:
var tbodyfistRowCells = tbody.querySelectorAll('tr:first-of-type > td');
for(i = 0; i < tbodyfistRowCells.length; i++){var tbodyColumnWidths = tbodyfistRowCells[i].offsetWidth;}
console.log(tbodyColumnWidths);
它只返回最后一個<td>
的 offsetWidth。 我需要每個<td>
的 offsetWidth。
我是 Javascript 的新手。 我確定我遺漏了一些明顯而重要的東西,我只是不知道要問互聯網搜索什么......
注意:這樣做的最終目標是當標題固定在我的頁面頂部時,使用<td>
的 offsetWidth 設置其各自<th>
的寬度(希望覆蓋固定列寬問題)。 如果你能告訴我如何使用一個數組的 offsetWidth 來改變它在另一個數組中的相應索引項(即td[2].offsetWidth = th[2].offsetWidth
)那將是一個很好的加分,雖然顯然不是主題這個問題。
試試這個(演示 - https://codepen.io/Alexander9111/pen/dyPwJvM )
const tbody = document.querySelector('tbody');
const tbodyfistRowCells = tbody.querySelectorAll('tr:first-of-type > td');
for(i = 0; i < tbodyfistRowCells.length; i++){
var tbodyColumnWidths = tbodyfistRowCells[i].offsetWidth;
console.log(i, tbodyfistRowCells[i].innerText)
console.log(i, tbodyColumnWidths)
}
注意我先找到<tbody>
元素
控制台輸出:
0 "A One"
0 44
1 "A Two"
1 45
2 "A Three"
2 54
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.