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

如何使用jQuery实现点击按钮打开datepicker日期选择器

实现点击自定义按钮显示jQuery UI Datepicker

你当前的代码存在冗余问题:每次点击按钮都会重复初始化datepicker,不仅低效还可能引发异常。正确的做法是一次性完成datepicker初始化并禁用输入框的默认触发行为,再通过按钮点击事件手动唤起选择器。

修改后的完整代码

<head>
<link href="https://code.jquery.com/ui/jquery-ui-git.css" rel="stylesheet" type="text/css" />
<script src="https://code.jquery.com/jquery-git.js"></script>
<script src="https://code.jquery.com/ui/jquery-ui-git.js"></script>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>自定义按钮触发Datepicker</title>
</head>
<body>
<p>Pick a date:</p>   
<p><input type="text" id="datepicker1" readonly /></p> 
<button id="bt">Date</button>

<script>
// 一次性初始化datepicker,禁用默认触发方式
$("#datepicker1").datepicker({
    showButtonPanel: true,
    showOn: "none" // 取消输入框或自带按钮的默认触发
});

// 点击自定义按钮时唤起日期选择器
$('#bt').click(function(){
    $("#datepicker1").datepicker("show");
});
</script>
</body>

关键细节说明

  • showOn: "none":彻底关闭datepicker的默认触发逻辑,让选择器仅受自定义按钮控制。
  • readonly:给输入框添加只读属性,避免用户手动输入日期,保证日期来源唯一。
  • datepicker("show"):jQuery UI Datepicker内置的手动唤起方法,直接调用即可显示选择器。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.04 02:35:20