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

如何默认激活Tom Select中的‘add’选项?

实现Tom Select默认高亮“添加”选项

完全可以实现,核心思路是在type事件触发后,定位到下拉菜单里的“添加”选项,再调用Tom Select的内置方法将其设为激活项。具体代码如下:

const tomSelect = new TomSelect(target, {
  create: true
});

tomSelect.on('type', function() {
  // 用setTimeout确保下拉菜单DOM已完成更新
  setTimeout(() => {
    // 定位默认的“添加”选项(Tom Select默认给它加了create-option类)
    const createOptionEl = this.dropdown.querySelector('.create-option');
    if (createOptionEl) {
      // 获取该选项对应的item数据
      const targetItem = this.options[createOptionEl.getAttribute('data-value')];
      if (targetItem) {
        // 设置为激活(高亮)项
        this.setActiveItem(targetItem);
      }
    }
  }, 0);
});

关键说明:

  • 使用setTimeout是因为type事件触发时,Tom Select可能还没完成下拉菜单的重新渲染,0延迟的定时器能保证我们操作的是最新的DOM结构。
  • 如果你自定义了“添加”选项的模板,需要把.create-option替换成你自己设置的类名或选择器。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.23 08:59:54