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

解决Choices-js重复初始化Select元素及选项更新失效问题

解决Choices-js重复初始化及年份选项不更新问题

问题根源

每次执行搜索调用set_date_filter_data时,你都会重新创建Choices实例,但目标元素已经绑定过实例,导致控制台出现Trying to initialise Choices on element already initialised警告;同时直接修改原生select的innerHTML不会同步到Choices的UI状态,所以选项不会更新。


方案一:复用Choices实例(推荐)

利用Choices官方API更新选项,避免重复初始化,效率更高:

  1. 先在全局作用域定义变量保存实例:
let yearChoicesInstance = null;
  1. 修改set_date_filter_data函数:
function set_date_filter_data(data) {
    console.log(year);
    // 构造符合Choices要求的选项数组
    const choicesList = [
        { value: 'all', label: 'All' },
        ...data.map(item => ({ value: item, label: item }))
    ];

    const element = document.getElementById('choices-year');
    
    if (!yearChoicesInstance) {
        // 首次初始化实例
        yearChoicesInstance = new Choices(element, {
            searchEnabled: true,
            searchPlaceholderValue: 'Search',
            itemSelectText: '',
            shouldSort: false,
        });
    } else {
        // 清空旧选项并设置新选项
        yearChoicesInstance.clearStore();
        yearChoicesInstance.setChoices(choicesList, 'value', 'label', true);
    }

    // 设置选中值
    const targetValue = year === '' ? 'all' : year;
    yearChoicesInstance.setChoiceByValue(targetValue);
}

方案二:销毁旧实例后重新初始化

如果必须重新初始化,先销毁已存在的实例再创建新的:

修改set_date_filter_data函数:

function set_date_filter_data(data) {
    console.log(year);
    let filter_options = '';
    filter_options += '<option value="all">All</option>';
    $.each(data, function (_a, b) {
        filter_options += '<option value="' + b + '">' + b + '</option>';
    });
    
    const element = document.getElementById('choices-year');
    element.innerHTML = filter_options;

    // 设置原生select选中值
    const targetValue = year === '' ? 'all' : year;
    element.value = targetValue;

    // 销毁已存在的Choices实例
    if (element.choices) {
        element.choices.destroy();
    }
    // 重新初始化实例
    element.choices = new Choices(element, {
        searchEnabled: true,
        searchPlaceholderValue: 'Search',
        itemSelectText: '',
        shouldSort: false,
    });
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.16 01:45:36