$.fn.modal.Constructor.prototype.enforceFocus = function () {
$("#insertModal").on("shown.bs.modal", function () {
$("#Ranks_Name").select2({
dropdownParent: $("#insertModal")
});
$("#Role").select2({
dropdownParent: $("#insertModal")
});
})
$("#updateModal").on("shown.bs.modal", function () {
$("#Ranks_Name1").select2({
dropdownParent: $("#updateModal")
});
$("#Role1").select2({
dropdownParent: $("#updateModal")
});
})
};
在普通頁面中使用Select2是正常的,但是在Modal中使用就發現了一些問題,首先如果在頁面加載完成后就調用
$(".select2").select2();是會有問題的,你會發現Modal框中的select顯示不正常,正確的做法是要改成
$("#editModal").on("shown.bs.modal", function(){
$(".select2").select2();
})
這是在Modal顯示出來后再初始select2。
但是又發現另一個問題,如果你的Modal定義是下面這樣的
<div class=" content modal fade" id="editModal" tabindex="-1" role="dialog" aria-labelledby="editModalLabel" aria-hidden="false">
你會發現select2的輸入框不能輸入,這時候把tabindex="-1"去掉就可以了。
還有一個方法是
在js 內加上下面這句
$.fn.modal.Constructor.prototype.enforceFocus = function () { };
經實際驗證,tabindex="-1"有時候不一定有效,加上上面這句是可以的
參考文章http://stackoverflow.com/questions/18487056/select2-doesnt-work-when-embedded-in-a-bootstrap-modal
https://www.cnblogs.com/sheldon-lou/p/3730905.html
https://blog.csdn.net/u013126379/article/details/53044933