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

如何给已初始化的ChoicesJS实例追加选项?

如何给已初始化的ChoicesJS实例追加选项?

问题重现

HTML代码

<select id="random-select"></select>

<button onclick="append()">
  Append new data to select
</button>

JavaScript代码

// 初始化插件
function init()
{
    const data = 
    {
        removeItemButton: true,
        duplicateItemsAllowed: false,
        searchEnabled: true,
        searchChoices: true,
    };
    
    const el = document.getElementById('random-select');
  
    new Choices(el, data);
}

function append()
{
    // 如何给已初始化的元素追加选项?
    const el = document.getElementById('random-select');
  
    // 无效
    el.setChoices([{ value: 1, label: 'test' }]);
    
     // 无效
    el.choices.setValue([{ value: 1, label: 'test' }]);
}

报错信息

  • setChoices is not a function
  • Cannot read properties of undefined (reading 'setValue')

解决方法

问题核心是你没有保存Choices的实例对象——Choices的方法只能通过实例调用,直接操作DOM元素是无效的。正确步骤如下:

  1. 初始化时将Choices实例存储起来(比如全局变量)
  2. 调用实例的setChoices方法,通过参数指定为追加模式(默认是替换全部选项)

修改后的代码:

// 全局存储Choices实例
let choicesInstance;

// 初始化插件
function init()
{
    const data = 
    {
        removeItemButton: true,
        duplicateItemsAllowed: false,
        searchEnabled: true,
        searchChoices: true,
    };
    
    const el = document.getElementById('random-select');
  
    // 保存实例
    choicesInstance = new Choices(el, data);
}

function append()
{
    // 调用实例方法,第四个参数传true实现追加
    choicesInstance.setChoices(
        [{ value: 1, label: 'test' }],
        'value',
        'label',
        true
    );
    
    // 也可以用更明确的参数写法:
    // choicesInstance.setChoices(
    //     [{ value: 1, label: 'test' }],
    //     'value',
    //     'label',
    //     'add'
    // );
}

说明

  • setChoices方法的第四个参数(部分版本为第三个)设为'add'或true时,会将新选项追加到现有列表,而非替换全部内容。
  • 所有Choices的API方法都必须通过初始化得到的实例调用,DOM元素本身不具备这些方法。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.05 12:06:25