如何给已初始化的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 functionCannot read properties of undefined (reading 'setValue')
解决方法
问题核心是你没有保存Choices的实例对象——Choices的方法只能通过实例调用,直接操作DOM元素是无效的。正确步骤如下:
- 初始化时将Choices实例存储起来(比如全局变量)
- 调用实例的
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
相关产品推荐
相关产品推荐

