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

SvelteKit:表格新增行时触发Toast与音效通知的实现问题

解决Svelte表格新增行时触发通知的问题

问题根源

你之前把on:change绑定在<td>上无效,是因为**<td>不是表单控件**,change事件只针对input、select这类能修改值的表单元素,静态文本单元格不会触发该事件。

推荐的Svelte专属解决方案

根据你的场景,有两种更可靠的实现方式:


方式1:监听Store的行数据变化(通用场景)

利用Svelte的反应式语句($:)监听$catStore.rows的数量变化,当行数增加时自动触发通知:

<script>
  function toastTrigger() {
    toast.push('新增一行!');
    // 播放音效的逻辑,和toast触发逻辑一致
    const notificationSound = new Audio('/path/to/your/sound.mp3');
    notificationSound.play().catch(err => console.error('音效播放失败:', err));
  }

  // 记录上一次的行数,用于对比是否新增了行
  let lastRowCount = 0;

  // 反应式监听Store中行数据的变化
  $: {
    const currentRowCount = Object.keys($catStore.rows).length;
    // 只有当行数增加时才触发通知
    if (currentRowCount > lastRowCount) {
      toastTrigger();
    }
    // 更新行数记录
    lastRowCount = currentRowCount;
  }
</script>

<!-- 表格正常渲染即可,无需在<td>绑定事件 -->
<table>
  <thead>
    <tr><th>名称</th></tr>
  </thead>
  <tbody>
    {#each Object.entries($catStore.rows) as [key, value], index (key)}
      <tr>
        <td>{value.name}</td>
      </tr>
    {/each}
  </tbody>
</table>

方式2:在添加行的逻辑中直接触发(更精准)

如果你的行是通过按钮点击、表单提交等主动操作添加的,直接在添加行的函数里调用toastTrigger是最直接的:

<script>
  function toastTrigger() {
    toast.push('新增一行!');
    const notificationSound = new Audio('/path/to/your/sound.mp3');
    notificationSound.play().catch(err => console.error('音效播放失败:', err));
  }

  // 假设这是你添加行的函数
  function addNewRow(newName) {
    // 生成唯一key(根据你的业务逻辑调整)
    const newKey = `row-${Date.now()}`;
    // 更新Store中的行数据
    $catStore.rows = {
      ...$catStore.rows,
      [newKey]: { name: newName }
    };
    // 直接触发通知
    toastTrigger();
  }
</script>

<!-- 添加行的按钮 -->
<button on:click={() => addNewRow('新名称')}>添加新行</button>

<!-- 表格正常渲染 -->
<table>
  <tbody>
    {#each Object.entries($catStore.rows) as [key, value], index (key)}
      <tr>
        <td>{value.name}</td>
      </tr>
    {/each}
  </tbody>
</table>

注意事项

  • 音效播放可能会被浏览器的自动播放策略限制,建议在用户有交互(比如点击按钮)后再触发,或者引导用户允许音频播放。
  • 如果你的catStore.rows是数组而不是对象,把Object.keys($catStore.rows).length改成$catStore.rows.length即可。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.29 02:37:39