【问题标题】:Find offsetWidth of EACH object in array -- Javascript (NO JQuery)在数组中查找每个对象的 offsetWidth -- Javascript (NO JQuery)
【发布时间】:2020-01-21 22:36:47
【问题描述】:

我已经为此寻找了几个小时的答案:

如何让 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>

我想在第一行中找到每个&lt;td&gt; 的 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);

它只返回最后一个&lt;td&gt; 的偏移宽度。我需要每个&lt;td&gt; 的 offsetWidth。

我是 Javascript 新手。我确定我遗漏了一些明显而重要的东西,我只是不知道该要求互联网搜索什么......

注意: 这样做的最终目标是使用 &lt;td&gt; 的 offsetWidth 来设置其各自的宽度 &lt;th&gt; 当标题固定到我的页面顶部时(希望覆盖固定的列宽问题)。如果您能告诉我如何使用一个数组的 offsetWidth 来更改其在另一个数组中的相应索引项(即td[2].offsetWidth = th[2].offsetWidth),那将是一个很大的优势,尽管显然不是这个问题的主题。

【问题讨论】:

    标签: javascript html


    【解决方案1】:

    试试这个(演示 - 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)
    }
    

    注意我首先找到&lt;tbody&gt; 元素

    控制台输出:

    0 "A One"
    0 44
    1 "A Two"
    1 45
    2 "A Three"
    2 54
    

    【讨论】:

    • 这太完美了! (我忘了在我的问题中包含我对 tbody 的定义。)console.log 中的“i”是关键。这就是我假设的索引号?
    • 不,我相信你的错误是你的console.log() 在你的循环之外,所以你改变了var tbodyColumnWidths 三次,然后只注销了一次。很高兴能提供帮助。
    • 啊,我明白了。谢谢你的澄清:)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-12-02
    • 2022-01-18
    相关资源
    最近更新 更多