查找数组中每个对象的offsetWidth--Javascript(无JQuery)
几个小时以来,我一直在寻找答案: 如何让console.log打印表中每个td的offsetWidth?(不使用JQuery) 假设我有这张桌子:查找数组中每个对象的offsetWidth--Javascript(无JQuery),javascript,html,Javascript,Html,几个小时以来,我一直在寻找答案: 如何让console.log打印表中每个td的offsetWidth?(不使用JQuery) 假设我有这张桌子: <table> <thead> <tr> <th>One</th>
<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>
一个
两个
三
一个
两个
三
B一
B二
B三
我想在第一行找到每个
的偏移网络宽度
我试过这个:
var tbodyfistRowCells = tbody.querySelectorAll('tr:first-of-type > td');
for(i = 0; i < tbodyfistRowCells.length; i++){var tbodyColumnWidths = tbodyfistRowCells[i].offsetWidth;}
console.log(tbodyColumnWidths);
var-tbodyfistRowCells=tbody.querySelectorAll('tr:type>td'的第一个);
对于(i=0;i
它只返回最后一个
的偏移宽度。我需要每个
的偏移宽度
我是Javascript新手。我肯定我错过了一些明显而重要的东西,我只是不知道该让互联网搜索什么
注:
这样做的最终目的是,当标题固定在我的页面顶部时,使用
的offsetWidth设置其相应
的宽度(希望覆盖固定列宽问题)。如果您能告诉我如何使用一个数组的offsetWidth来更改另一个数组中相应的索引项(即td[2]。offsetWidth=th[2]。offsetWidth
),这将是一个很好的优点,但显然不是这个问题的主题。试试这个(演示-)
这太完美了!(我忘了在我的问题中包含我对tbody的定义。)console.log中的“I”是关键。这调用了我假设的索引号?不,我相信您的错误是将
console.log()
放在循环之外,所以您更改了var-tbodyColumnWidths
三次,但只注销了一次。很高兴能帮上忙。啊,我明白了。感谢您的澄清:)
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)
}
0 "A One"
0 44
1 "A Two"
1 45
2 "A Three"
2 54