使用 javascript 将 TBODY 列表添加到表时,TBODY 属性丢失

问题描述 投票:0回答:0

我使用 JS 将 TBODY 列表添加到表中,但在生成的 HTML 中,每个添加的 tbody 的属性都丢失了

我需要这个结构用于 Stimulus 控制器。

<html lang="it">
<body>
     <table>
        <tbody class="tbody" data-value="hello">
            <tr>
                <td>a row in 1st block</td>
            </tr>
        </tbody>
        <tr class="last-block-element">
            <td>last element of 1st block</td>
        </tr>
        <tbody class="tbody" data-value="hello">
            <tr>
                <td>a row in 2nd block</td>
            </tr>
        </tbody>
        <tr class="last-block-element">
            <td>last element of 2nd block</td>
        </tr>
    </table>
</body>
<script>
    const tbody = document.querySelector('.tbody')
    const lastBlockElements = document.querySelectorAll('.last-block-element')
    const newBody = `<tbody class="tbody" data-value="new-body">
                        <tr>
                            <td>another row</td>
                        </tr>
                    </tbody>`
    lastBlockElements.forEach(element => {
        element.insertAdjacentHTML('beforebegin', newBody);
    })
</script>
</html>

这是结果: the executed code

javascript html stimulusjs
© www.soinside.com 2019 - 2024. All rights reserved.