如何通过Bootstrap Datepicker的前后月箭头切换时修改URL
解决Bootstrap Datepicker切换月份箭头时修改URL的问题
要实现点击上下月箭头时修改URL,核心是利用Bootstrap Datepicker提供的**changeDate事件**——这个事件不仅会在选择日期时触发,还会在切换月份/年份、点击今日按钮等视图变更场景下触发,刚好覆盖你的需求。
修改后的代码
$(function(){ $('#datetable') .datepicker({ format: "dd/mm/yyyy", todayHighlight: true, clearBtn: true, daysOfWeekDisabled: [0, 6], daysOfWeekHighlighted: "0,6", changeMonth: false }) .on('changeDate', function(e) { // 获取当前选中的日期,若未选中则取当前视图的日期 const targetDate = e.date || $('#datetable').datepicker('getViewDate'); const pickedDate = $(this).val(); // 更新提示文本 if (pickedDate){ $("#showdate").text(`You picked ${pickedDate}.`); } else { $("#showdate").text(`No date chosen.`); } // 提取年、月、日(未选中日期时默认当月第一天) const year = targetDate.getFullYear(); const month = targetDate.getMonth() + 1; const day = pickedDate ? targetDate.getDate() : 1; // 跳转到目标URL window.location.assign(`https://bloxool-simple.testing.com.co/test/helloworld.php&year=${year}&month=${month}&day=${day}`); }); });
关键说明
- 替换事件监听:把原来的
change事件替换为changeDate事件,覆盖所有视图变更场景(包括切换月份箭头)。 - 日期获取逻辑:
- 若用户选中了日期,使用
e.date获取选中日期; - 若只是切换月份未选日期,用
getViewDate()获取当前视图显示的月份日期,默认取当月第一天作为day参数。
- 若用户选中了日期,使用
- 修正冗余代码:移除了
getDate(date)这类多余的参数传递,原生日期方法不需要额外传参。
备选方案(监听箭头点击)
如果changeDate事件在你的版本中不生效,也可以直接监听箭头按钮的点击事件(依赖DOM类名,兼容性稍差):
$(function(){ $('#datetable').datepicker({ format: "dd/mm/yyyy", todayHighlight: true, clearBtn: true, daysOfWeekDisabled: [0, 6], daysOfWeekHighlighted: "0,6", changeMonth: false }).change(function() { // 保留原有的选择日期逻辑 let pickedDate = $(this).val(); if (pickedDate){ $("#showdate").text(`You picked ${pickedDate}.`); var date = $('#datetable').datepicker('getDate'); const year = date.getFullYear(); const month = date.getMonth() + 1; const day = date.getDate(); window.location.assign(`https://bloxool-simple.testing.com.co/test/helloworld.php&year=${year}&month=${month}&day=${day}`); } else { $("#showdate").text(`No date chosen.`); } }); // 监听上下月箭头点击 $(document).on('click', '.datepicker-prev, .datepicker-next', function() { setTimeout(function() { const viewDate = $('#datetable').datepicker('getViewDate'); const year = viewDate.getFullYear(); const month = viewDate.getMonth() + 1; const pickedDate = $('#datetable').val(); const day = pickedDate ? $('#datetable').datepicker('getDate').getDate() : 1; window.location.assign(`https://bloxool-simple.testing.com.co/test/helloworld.php&year=${year}&month=${month}&day=${day}`); }, 100); // 延迟确保视图已更新 }); });
内容的提问来源于stack exchange,提问作者André Tex
相关产品推荐
相关产品推荐

