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

bsmultiselect如何获取用户选中的选项列表或数组

问题描述

我在项目中用到了bsmultiselect库,它的界面效果不错,但官方文档不够完善,我找不到获取用户选中选项列表的方法,希望大家能给点相关提示。
我目前写的代码如下:

const instSel = document.getElementById('instrument-select');

let x = new xhr();

x.get("GET", "instruments.json", (rsp) => {
    instr = JSON.parse(rsp)
    for (i in instr) {
        let optGr = document.createElement("optgroup");
        optGr.setAttribute("label", instr[i]["name"]);
        for (x in instr[i]["instruments"]) {
            let opt = document.createElement("option");
            opt.setAttribute('value', instr[i]["instruments"][x]);
            opt.setAttribute('class', 'dropdown-item');
            opt.textContent = instr[i]["instruments"][x];
            optGr.appendChild(opt);
        }
    instSel.appendChild(optGr);
    console.log(optGr);
    }
    bs = dashboardcode.BsMultiSelect("#instrument-select");
    console.log(bs);
});

document.body.addEventListener('dblclick', () => {
    console.log(bs.getPicks()); // 这个方法只能返回HTML元素
});

我后续通过监听e.target事件成功拿到了需要的数据,实现代码如下:

instSel.onchange = (e) => {
    // 遍历所有选项
    for (let i = 0; i < e.target.length; i++) {
        if (e.target[i].selected) { // 判断选项是否被选中
            console.log(e.target[i].textContent)
        }
    }
}

解答

你自己实现的方案是可行的,bsmultiselect本质是对原生select元素的封装,所有选中状态都会同步回原生的option节点上,直接读取原生属性是兼容性最好的方案。
还可以用更简洁的写法批量获取选中项,不需要手动遍历:

instSel.onchange = (e) => {
    // 直接获取所有选中的option
    const selectedOptions = Array.from(e.target.selectedOptions);
    // 提取选中项的文本内容
    const selectedTexts = selectedOptions.map(opt => opt.textContent);
    // 提取选中项的value值
    const selectedValues = selectedOptions.map(opt => opt.value);
    
    console.log('选中的文本:', selectedTexts);
    console.log('选中的值:', selectedValues);
}

如果需要随时主动获取选中项,不需要等change事件触发,也可以直接读取原生select节点的selectedOptions属性:

function getSelectedItems() {
    const selectedOptions = Array.from(instSel.selectedOptions);
    return {
        texts: selectedOptions.map(opt => opt.textContent),
        values: selectedOptions.map(opt => opt.value)
    };
}

// 随时调用即可拿到当前选中项
console.log(getSelectedItems());

你之前调用的getPicks()方法返回的是渲染用的DOM节点,适合要自定义修改选中项UI的场景,拿数据的话直接读原生select的属性效率更高也更稳定。

内容的提问来源于stack exchange,提问作者era-net

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.27 13:24:10