Jquery Mobile DateBox点击Set按钮时时间重置且无法获取时间
解决Jtsage DateBox点击Set时间重置、无法获取值的问题
我帮你排查了代码里的几个关键问题,这应该就是导致时间重置、无法获取值的核心原因:
1. 脚本加载顺序错误 + 重复jQuery冲突
你当前的脚本加载顺序完全颠倒了,而且同时引入了两个不同版本的jQuery(1.9.0和1.11.1),这会导致DateBox无法正确依赖jQuery和jQuery Mobile初始化,进而引发组件功能异常。
正确的加载顺序应该是:
- 单个版本的jQuery → jQuery Mobile CSS → jQuery Mobile JS → DateBox CSS → DateBox JS
2. DateBox配置时机不正确
全局配置应该绑定到jQuery Mobile的pagecreate事件中(因为jQuery Mobile采用动态页面创建机制),确保配置在页面初始化时生效,而不是在资源加载前执行。
3. 修正后的完整代码
<!-- 加载单个稳定版本的jQuery --> <script src="http://code.jquery.com/jquery-1.11.1.min.js"></script> <!-- jQuery Mobile样式文件 --> <link href="http://code.jquery.com/mobile/1.4.5/jquery.mobile-1.4.5.min.css" rel="stylesheet"/> <!-- jQuery Mobile核心脚本 --> <script src="http://code.jquery.com/mobile/1.4.5/jquery.mobile-1.4.5.min.js"></script> <!-- DateBox样式文件 --> <link href="https://cdn.jsdelivr.net/npm/jtsage-datebox-jqm@4.3.1/jtsage-datebox.min.css" rel="stylesheet"/> <!-- DateBox核心脚本 --> <script src="https://cdn.jsdelivr.net/npm/jtsage-datebox-jqm@4.3.1/jtsage-datebox.min.js"></script> <script> $(document).on("pagecreate", "#attendanceMarkPage", function() { // 在页面创建时配置DateBox全局选项 $.extend($.jtsage.datebox.prototype.options, { useInline: true, hideInput: true, overrideSlideFieldOrder: ['y','m','d','h','i'], dateFormat: "%Y-%m-%d %H:%i", useHeader: false }); // 绑定DateBox确认事件,确保值正确更新不重置 $("#attendanceMarkTime").on("datebox", function(e, p) { if (p.method === "set") { // 获取选中的时间值 var selectedTime = $(this).val(); // 同步到隐藏输入框(用于表单提交) $("#attendanceMarkEmployee").val(selectedTime); console.log("选中的时间:", selectedTime); } }); }); </script> <div data-role="page" id="attendanceMarkPage"> <div data-role="header" data-theme="a"> <a href="#mainPage" class="ui-btn ui-shadow ui-icon-arrow-l ui-btn-icon-notext ui-btn-inline"></a> <h1>Salary</h1> </div><!-- /header --> <div role="main" class="ui-content"> <form class="ui-filterable"> <div class="ui-field-contain"> <label for="attendanceMarkTime">Time:-</label> <input name="themee" id="attendanceMarkTime" data-role="datebox" data-datebox-mode="slidebox" readonly="readonly" type="text" data-options='{"useInline": true, "hideInput": true}' > <input type="hidden" name="attendanceTime" id="attendanceMarkEmployee"/> </div> </form> </div> </div>
关键修改说明
- 移除了重复的jQuery引入,统一使用1.11.1版本避免冲突
- 严格按照依赖顺序加载资源,确保DateBox能正确找到依赖库
- 将DateBox配置放在
pagecreate事件中,适配jQuery Mobile的动态页面生命周期 - 添加了
datebox事件监听,在点击Set按钮时主动获取并同步值,彻底解决重置问题 - 修正了input的
data-options属性,确保配置正确传递到组件
如何获取时间值
你可以通过以下两种方式获取选中的时间:
- 直接读取输入框的值:
$("#attendanceMarkTime").val() - 在上述
datebox事件的set方法回调中获取,同时同步到隐藏输入框(适合表单提交场景)
内容的提问来源于stack exchange,提问作者Ramesh Kithsiri HettiArachchi
相关产品推荐
相关产品推荐

