在 bootstrap 多选控件元素中被选中 index/indices

Get selected index/indices in a bootstrap multiselect control element

我有一个 Bootstrap 多选元素,看起来像这样:

我知道如何检索所选项目的值,即 $('#multiselectElement').val();

此代码可以 return 例如['Cheese', 'Mozzarella,', 'Onions']

问题是,我需要的不是物品价值,而是它们的指数。我的意图是 return [0, 2, 5] 而不是 ['Cheese', 'Mozzarella,', 'Onions'].

我该怎么做?

让你的价值观成为索引...

<select id="example-single">
    <option value="0">Cheese</option>
    <option value="1">Tomato</option>
    <option value="2">Mozzarella</option>
    <option value="3">Onions</option>
    ...
</select>

Select 选项元素...

$('#multiselectElement option:selected').map(function(a, item){return item.value;});

获取点击项的索引:

$('#multiselectElement *').click(function(){
$(this).index()
});