You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Bootstrap模态框与jQuery UI Datepicker冲突:月份选择框闪退问题

Bootstrap模态框与jQuery UI Datepicker月份选择冲突的解决方法

问题现象

点击Bootstrap模态框内的jQuery UI Datepicker月份选择下拉框时,模态框会立即关闭,无法正常完成月份选择操作。

复现步骤:

  • 点击“Launch demo modal”按钮打开模态框
  • 点击输入框激活Datepicker组件
  • 点击月份选择下拉框,模态框随即关闭

问题原因

Bootstrap模态框默认会在点击模态框外部区域时触发关闭逻辑,而jQuery UI的Datepicker下拉菜单(包括月份选择的<select>元素)是渲染在模态框的DOM结构之外的,所以点击这个下拉框时,会被Bootstrap判定为“点击了模态框外部”,从而触发关闭事件。

解决方案

通过阻止Datepicker月份选择元素的点击事件向上冒泡,避免触发Bootstrap模态框的关闭逻辑。具体实现如下:

修改后的完整代码

JavaScript部分

$(function() {
  $("#datepicker").datepicker({
    changeMonth: true
  });

  // 阻止月份选择下拉的点击事件冒泡,避免触发模态框关闭
  $(document).on('click', '.ui-datepicker-month', function(e) {
    e.stopPropagation();
  });
});

HTML部分

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/js/bootstrap.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jqueryui/1.11.0/jquery-ui.min.js"></script>
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.css"/>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/jqueryui/1.11.0/jquery-ui.min.css"/>

<!-- Button trigger modal -->
<button type="button" class="btn btn-primary" data-toggle="modal" data-target="#exampleModal">
  Launch demo modal
</button>

<!-- Modal -->
<div class="modal fade" id="exampleModal" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel" aria-hidden="true">
  <div class="modal-dialog" role="document">
    <div class="modal-content">
      <div class="modal-header">
        <h5 class="modal-title" id="exampleModalLabel">Modal title</h5>
        <button type="button" class="close" data-dismiss="modal" aria-label="Close">
          <span aria-hidden="true">&times;</span>
        </button>
      </div>
      <div class="modal-body">
        <input id="datepicker">
      </div>
      <div class="modal-footer">
        <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
        <button type="button" class="btn btn-primary">Save changes</button>
      </div>
    </div>
  </div>
</div>

原理说明

.ui-datepicker-month是jQuery UI Datepicker为月份选择下拉框自动添加的类名,通过给该元素绑定点击事件并调用e.stopPropagation(),可以阻止事件向上传递到模态框的关闭监听逻辑,从而避免模态框误关闭。

内容的提问来源于stack exchange,提问作者CIRCLE

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.12 09:43:41