如何让Tom Select初始化时显示为空而非默认选中首个选项?
如何让Tom-Select初始化时保持选择框为空?
要解决Tom-Select初始化自动选中第一个选项的问题,有两个实用方案:
方案一:添加空默认选项(推荐)
在原生<select>最前面加一个值为空字符串的空选项,Tom-Select会自动将其识别为未选中的初始状态,完美匹配需求:
<link href="https://cdn.jsdelivr.net/npm/tom-select@2.2.2/dist/css/tom-select.css" rel="stylesheet"> <script src="https://cdn.jsdelivr.net/npm/tom-select@2.2.2/dist/js/tom-select.complete.min.js"></script> <select id="ex-dropdown-input" autocomplete="off" placeholder="How cool is this?"> <!-- 新增空默认选项 --> <option value=""></option> <option>amazing</option> <option>awesome</option> <option>cool</option> <option>excellent</option> <option>great</option> <option>neat</option> <option>superb</option> <option>wonderful</option> </select>
JS代码保持原有配置即可:
new TomSelect('#ex-dropdown-input',{ plugins: ['dropdown_input', 'remove_button'], allowEmptyOption:true, });
方案二:初始化后手动清空
如果无法修改HTML结构,可在Tom-Select实例化完成后,调用clear()方法强制清空选中状态:
const tsInstance = new TomSelect('#ex-dropdown-input',{ plugins: ['dropdown_input', 'remove_button'], allowEmptyOption:true, }); // 初始化完成后立即清空选中项 tsInstance.clear();
这两种方法都能实现加载时选择框完全为空的效果,根据实际场景选择即可。
内容的提问来源于stack exchange,提问作者Cornelius
相关产品推荐
相关产品推荐

