如何使用JavaScript/jQuery获取select所有option并按sid分组存入对象
实现方案
下面分别提供原生JavaScript和jQuery两种实现方式:
原生JavaScript实现
const res = {}; // 选中所有option元素遍历 document.querySelectorAll('#listOfOptions option').forEach(opt => { const sid = opt.getAttribute('sid'); const val = opt.value; // 对应sid不存在时先初始化空数组 if (!res[sid]) res[sid] = []; res[sid].push(val); }); console.log(res);
jQuery实现
const res = {}; $('#listOfOptions option').each(function() { const sid = $(this).attr('sid'); const val = $(this).val(); if (!res[sid]) res[sid] = []; res[sid].push(val); }); console.log(res);
注:你示例中给出的输出格式里用小括号包裹的集合并非JavaScript标准语法,上述实现默认用数组存储对应sid的value集合,最终输出结构如下,完全符合业务需求:
{ '15': ['test', 'test2'], '16': ['plah', 'plah2'] }
内容的提问来源于stack exchange,提问作者Loai Alnshar
相关产品推荐
相关产品推荐

