如何通过选项文本获取Chosen.js下拉选择框的对应值?
通过选项文本获取Chosen下拉框对应值的解决方案
嘿,我来帮你搞定这个Chosen组件的问题!其实Chosen只是把原生的<select>给隐藏了,并没有替换原选项的值——你看到的数字应该是Chosen生成UI时用的内部标识,原生select的option值其实还好好待在DOM里呢。下面给你两种可靠的解决方法:
方法一:直接操作原生select(最推荐)
这是最稳妥的方式,因为原生select的结构不会随Chosen版本变化,我们直接从它里面找对应文本的option就行:
function getChosenValueByText(selectId, targetText) { // 拿到被隐藏的原生select元素 const selectElement = document.getElementById(selectId); if (!selectElement) return null; // 遍历所有option项 for (const option of selectElement.options) { // 这里可以根据需求调整匹配规则,比如忽略大小写、去掉前后空格 if (option.textContent.trim() === targetText.trim()) { return option.value; } } // 没找到匹配项就返回null return null; } // 举个例子:假设你要找文本为"..."的选项值 const targetValue = getChosenValueByText('selOIG', '...'); console.log(targetValue); // 会输出对应的value,比如你示例里的"0"
拿到值之后,如果需要更新Chosen的选中状态,记得触发它的更新事件:
// 用jQuery的写法(Chosen通常配合jQuery使用) $('#selOIG').val(targetValue).trigger('chosen:updated');
方法二:操作Chosen生成的UI元素(不推荐)
如果你非要直接碰Chosen生成的DOM结构,也能实现,但要注意不同版本的Chosen可能会改UI结构,所以这个方法比较脆弱:
function getChosenValueByTextFromChosenUI(selectId, targetText) { const chosenContainer = document.getElementById(`${selectId}_chzn`); if (!chosenContainer) return null; // 找到Chosen下拉列表里的所有选项 const optionItems = chosenContainer.querySelectorAll('.chzn-results li'); for (const item of optionItems) { if (item.textContent.trim() === targetText.trim()) { // 从data属性里取出对应的option值 return item.getAttribute('data-option-attribute'); } } return null; }
小提示
- 优先选方法一,稳定性拉满!
- 如果需要模糊匹配(比如文本包含某个关键词就行),可以把
===换成includes(),比如option.textContent.includes(targetText)。
内容的提问来源于stack exchange,提问作者Kuubs
相关产品推荐
相关产品推荐

