<选项>在<选择>中的互斥

Mutual exclusion for <option>s in a <select>?

本文关键字:选项 选择      更新时间:2023-09-26

我需要将单选和多选的功能组合到一个控件中。 具体来说,我有很多选择。 第一个与其他的相互排斥。 因此,如果我选择第一个,它需要取消选中所有其他选项。 如果选择了其中一个,则必须取消选中第一个(如果选择)。 其他选项应该不会相互影响。

<select id="myGroup" data-native-menu="false" multiple="multiple" >
    <option value=""  >Select Group(s)</option>
    <option value="-1" selected="selected" >I am alone</option>
    <option value="1"  >I am not alone 1</option>
    <option value="2"  >I am not alone 2</option>
    <option value="3"  >I am not alone 3</option>
</select>

我安装了一个 onchange() 处理程序。 所以,我知道什么时候做出选择。 但我似乎无法分辨刚刚选择了哪个选项。 因此,在上面的例子中,如果用户选择选项 3,$(this).val() 将变为 -1,3。 我怎么知道是刚刚被选中的"3"?

到目前为止,我想出的唯一办法是保留一个选定选项的数组,然后在选择新选项时对数组进行差异。

$('select[id=myGroup]').change(function() {
    // At this point, I know the sum total of what's been selectec.
    // But I don't know which one just got added to the list.
    // I want logic that says:
    //  if -1 just got added, then unselect all the others
    //  if something else was just added, make sure that -1 is not selected
    var selected = $(this).val();
    alert(JSON.stringify(selected));
});

有没有更好的方法?

您只需要保留第一个选项的状态,而不是所有选项:

var firstOption = $("#myGroup > option[value=-1]");
var firstSelectedBefore = firstOption.prop("selected");
$("#myGroup").on("change", function(event) {
    if (firstOption.prop("selected") && this.selectedOptions.length > 1) {
        if (firstSelectedBefore) { // non-first option just selected
            firstOption.prop("selected", false);
        } else { // first option just selected
            $(this).find("option:not([value=-1])").prop("selected", false);
        }
    }
    firstSelectedBefore = firstOption.prop("selected");
});