Esc 键关闭 bootstrap 模态但不关闭其中的 select2 下拉菜单

esc key close bootstrap modal but doesn't close select2 dropdown inside it

我在我的下拉列表中实现了 select2,它位于 bootstrap 模态 window.

<div class="modal-body">
...
<div class="controls">
    @Html.DropDownList("Experts", new SelectList(Model.ExpertsInfo, "UserId", "FullName"),
      string.Empty, new { @class = "select", id = "expert-select", autocomplete = "true", autofocus = "", style = "width: 295px;" }                       
                </div>
...
    </div>

 $("#experts").select2({
            allowClear: true,
            minimumResultsForSearch: -1,
            formatNoMatches: function () {
                return "@CommonResources.NoMatches";
            }
        });

一切正常,但如果我关闭模态 window,当下拉菜单打开时,模态 window 隐藏但下拉仍然存在!我哪里出错了?我必须实现自己的处理程序对于 esc 键?

选择2 API

要关闭 select2,请使用以下命令:

 $('#experts').select2("close");

然后您将根据 bootstrap 的版本进入关闭事件:

Bootstrap 3

$('#myModal').on('hidden.bs.modal', function () {
  $('#experts').select2("close");
})

Bootstrap 2

$('#myModal').on('hidden', function () {
   $('#experts').select2("close");
})

最终解

根据安东的评论:

$('#expert-modal').keyup(function (e) { if (e.keyCode == 27) {
       $('#s2id_experts').select2("close"); 
    } 
});