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

如何确定当前打开的jQuery UI Datepicker关联的输入框?

获取当前打开的jQuery Datepicker对应的输入框

方法1:通过onOpen事件跟踪当前输入框

初始化Datepicker时,利用官方公开的onOpen和onClose事件,记录当前激活的输入框实例,点击检查按钮时直接读取该记录即可。这种方式依赖官方API,兼容性和稳定性更好。

$(function() {
  let activeDatepickerInput = null;

  // 批量初始化所有输入框的Datepicker,绑定跟踪事件
  $("#input1, #input2, #input3").datepicker({
    onOpen: function() {
      activeDatepickerInput = $(this);
    },
    onClose: function() {
      activeDatepickerInput = null;
    }
  });

  $("#check").on("click", function() {
    if ($("#ui-datepicker-div:visible").length > 0 && activeDatepickerInput) {
      alert(`当前打开日期选择器的输入框ID是:${activeDatepickerInput.attr('id')}`);
    } else {
      alert("没有打开的日期选择器");
    }
  });
});

方法2:直接访问Datepicker内部实例

jQuery UI Datepicker会维护一个内部的当前活跃实例$.datepicker._curInst,其中的input属性就是对应的输入框DOM元素。这种方式无需额外事件绑定,代码更简洁,但依赖内部实现细节,若后续jQuery UI版本更新可能失效,适合旧项目快速适配。

$(function() {
  $("#input1").datepicker();
  $("#input2").datepicker();
  $("#input3").datepicker();

  $("#check").on("click", function() {
    const datepickerVisible = $("#ui-datepicker-div:visible").length > 0;
    if (datepickerVisible && $.datepicker._curInst) {
      const activeInput = $($.datepicker._curInst.input);
      alert(`当前打开日期选择器的输入框ID是:${activeInput.attr('id')}`);
    } else {
      alert("没有打开的日期选择器");
    }
  });
});

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.12 18:42:33