【问题标题】:jQuery - prevent option deselect in select multiplejQuery - 防止在选择多个选项中取消选择
【发布时间】:2014-02-05 21:28:21
【问题描述】:

是否可以防止在多选控件中取消选择某个选项?此外,它不得取消选择任何其他选定的选项。我试过了:

$('#selections option').click(function(){
    $(this).prop('selected', true);
});

似乎不起作用。有谁知道我怎么能做到这一点?

【问题讨论】:

  • 选项通常不会触发鼠标事件,所以我会说不?

标签: jquery


【解决方案1】:

这是一种方法

$('#selections').on('change', function(e) {
    var self = this,
        selected = $(this).data('selected') || [];

    $.each(selected, function(_,i) {
        $('option', self).eq(i).prop('selected', true)
    });

    $(this).data('selected', $.map($('option:selected', this), function(el) {
        return $(el).index();
    }));
});

FIDDLE

【讨论】:

    【解决方案2】:

    已经试过了吗?:

    $('#selections option').click(function(evt){
        evt.preventDefault();
        $(this).prop('selected', true);
    });
    

    【讨论】:

    • 如果你提出这个解决方案,那么建议它而不是质疑它。并通过edit回答答案来解释为什么这样做。
    【解决方案3】:

    试试这个:

    $("#selections").click(function () {
        $("#option_always_selected").prop('selected', true);
    });
    

    【讨论】:

      猜你喜欢
      • 2012-10-22
      • 1970-01-01
      • 1970-01-01
      • 2023-03-08
      • 2023-03-16
      • 1970-01-01
      • 1970-01-01
      • 2019-04-16
      • 2017-08-13
      相关资源
      最近更新 更多