提问人:angry kiwi 提问时间:11/16/2023 最后编辑:angry kiwi 更新时间:11/16/2023 访问量:49
如何有条件地设置表行的类 |SvelteKit (英语)
How to conditionally set classes for table rows | SvelteKit
问:
我在 SvelteKit 项目中有以下代码:
<table class="AddressTable">
<thead>
<tr>
<th>id</th>
<th>contact</th>
</tr>
</thead>
<tbody>
{#each gooddata as item, i}
<tr class="bg-rose-200">
<td>{i + 1}</td>
<td class="nine">{#if item.contact} {item.contact} {/if}</td>
</tr>
{/each}
</tbody>
</table>
如您所见,表行类现在是 bg-rose-200。
我希望表行在item.country上具有不同的类基础。
例如,如果该行的类为 bg-green-200item.country == 'uk
如果该行将有类item.country == 'us
bg-black-200
如果该行将有类item.country == 'canada
bg-yellow-200
如果该行的类为 bg-purple-200item.country == 'singapore
怎么做?
答:
3赞
Connie
11/16/2023
#1
我使用的是 Svelte 而不是 SvelteKit,所以如果这不适用于您的问题,请深表歉意。
我添加了以下函数,基本上只是检查一个字符串并返回一个字符串,在本例中是你的类。这不是最有效的方法,但它可能适合您。
const handleContryClass = (country) => {
if (country === 'uk') return 'bg-green-200'
if (country === 'us') return 'bg-black-200'
if (country === 'canada') return 'bg-yellow-200'
if (country === 'singapore') return 'bg-purple-200'
//add other classes
return 'bg-rose-200' // Default class
}
然后在 HTML 中像这样调用函数。
<table class="AddressTable">
<thead>
<tr>
<th>id</th>
<th>contact</th>
</tr>
</thead>
<tbody>
{#each gooddata as item, i}
<tr class={handleContryClass(item.country)}>
<td>{i + 1}</td>
<td class="nine">{#if item.contact} {item.contact} {/if}</td>
</tr>
{/each}
</tbody>
</table>
评论
Class Directive