1 回答
TA贡献1848条经验 获得超10个赞
您可以遍历level-0选择中的每个选项,将它们的文本添加为标签,将它们的同级level-1选项文本作为项目添加到对象中。然后你可以将这些对象推送到一个数组来生成你想要的结构:
let options = [];
$('.items option.level-0').each(function(_, el) {
let label = $(el).text();
let items = [];
el = $(el).next();
while (el.length && el.attr('class').split(/\s+/).includes('level-1')) {
items.push(el.text());
el = el.next();
}
options.push({
label,
items
});
});
console.log(options);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<select class="items">
<option value="0" selected="selected">All Types Of Staff</option>
<option class="level-0 main-option-1" value="12">Main Option 1</option>
<option class="level-1 sub-option-1" value="29">Sub Option 1</option>
<option class="level-1 sub-option-2" value="30">Sub Option 2</option>
<option class="level-0 main-option-2" value="11" selected="selected">Main Option 2</option>
<option class="level-1 sub-option-1" value="28">Sub Option 1</option>
<option class="level-1 sub-option-2" value="25">Sub Option 2</option>
<option class="level-1 sub-option-3" value="26">Sub Option 3</option>
<option class="level-1 sub-option-4" value="27">Sub Option 4</option>
<option class="level-0 main-option-3" value="10">Main Option 3</option>
<option class="level-1 sub-option-1" value="22">Sub Option 1</option>
<option class="level-1 sub-option-2" value="23">Sub Option 2</option>
</select>
添加回答
举报