You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在daisyui表格中点击切换category.urgency布尔值?

解决表格布尔值点击切换不生效的问题

直接在插值文本上绑定on:click事件是无效的,因为文本节点不支持事件绑定。你需要把category.urgency包裹在可交互的HTML元素中,再绑定点击事件来实现布尔值切换。以下是修改后的代码:

<table class="table w-full">
  <!-- Headers -->
  <thead>
    <tr>
      <th />
      <th>Category</th>
      <th>Urgency</th>
    </tr>
  </thead>
  <tbody>
    {#each categories as category, i}
      <tr class="capitalize">
        <td>{i+1}</td>
        <td>{category.name}</td>
        <td>
          <!-- 用span包裹布尔值,添加点击事件和交互样式 -->
          <span 
            class="cursor-pointer px-2 py-1 rounded-full {category.urgency ? 'bg-red-100 text-red-800' : 'bg-gray-100 text-gray-800'}"
            on:click={() => category.urgency = !category.urgency}
          >
            {category.urgency ? 'Urgent' : 'Not Urgent'}
          </span>
        </td>
      </tr>
    {/each}
  </tbody>
</table>

关键说明:

  • 用<span>包裹布尔值,并添加cursor-pointer类提示用户可点击,同时用Tailwind/DaisyUI样式区分不同状态的视觉效果
  • 直接在on:click中切换category.urgency的值,Svelte会自动响应这个变化并更新视图
  • 如果你的categories是不可变数据(比如从API获取的只读数组),可能需要创建副本后修改,确保响应式生效:
    function toggleUrgency(category) {
      const index = categories.findIndex(c => c.id === category.id);
      categories = [...categories];
      categories[index].urgency = !categories[index].urgency;
    }
    
    然后在on:click中调用toggleUrgency(category)即可。

内容的提问来源于stack exchange,提问作者user20840709

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.06 06:55:58