如何使用 Svelte 将 CSS 属性绑定到 Table 单元格

How to Bind an CSS attribute to a Table Cell with Svelte

我知道使用 Svelte(或任何其他框架)直接访问 DOM 不是一个好主意,例如。 document.getElementById 然后对它做点什么。我有一个非动态 table 已经作为 Svelte 组件在页面上,然后我还有以下数据:一个数组表示 table 行的单元格(假设我每行有 5 个单元格)还有另一个数组,其中每个元素都有索引号,我必须在对应的 table 单元格中添加 CSS 属性 active='1'

例如:arrIdxs = [1,3,4]arrCells = [a,b,c,d,e]

<table>
<tr>
<td>a</td>
<td active="1">b</td>
<td>c</td>
<td active="1">d</td>
<td active="1">e</td>
</tr>
</table>

实现该目标的好方法是什么?

我不确定我是否理解用例,但您必须这样做:

<script>
    const arrIdxs = [1, 3, 4];
    const arrCells = ['a', 'b', 'c', 'd', 'e'];
</script>

<table>
    <tr>
        {#each arrCells as cell, index}
            <td class:active={arrIdxs.includes(index)}>{cell}</td>
        {/each}
    </tr>
</table>

<style>
    .active {
        background-color: red;
    }
</style>