如何模拟点击打开Bootstrap datetimepicker日历(非直接点击输入框)
无需点击输入框打开Bootstrap datetimepicker日历的方法
页面上存在一个Bootstrap datetimepicker元素,希望不用直接点击输入框就能打开对应的日历,但尝试多种模拟点击事件的方法都无效。
对应元素代码
<div class="input-group date basedatefield"> <input type="text" name="basefield" autocomplete="off" readonly="" class="form-control" id="id_basefield" dp_config="{"id": "dp_37", "picker_type": "DATE", "linked_to": null, "options": {"showClose": false, "showClear": true, "showTodayButton": false, "format": "MM/DD/YYYY", "useCurrent": false, "ignoreReadonly": true, "keepInvalid": true}}"> <div class="input-group-addon input-group-append" data-target="#basedatetimepicker1" data-toggle="datetimepickerv"> <div class="input-group-text"><i class="glyphicon glyphicon-calendar"></i></div> </div> </div>
已尝试但无效的代码
document.getElementById('id_basefield').click(); document.getElementsByClassName('basedatefield')[0].click(); document.getElementsByClassName('input-group')[0].click();
可行解决方案
直接调用Bootstrap datetimepicker插件的API方法显示日历,而非模拟DOM元素点击:
- jQuery方式调用
// 确保插件已完成初始化后执行 $('#id_basefield').data('datetimepicker').show();
- 原生JavaScript方式
先获取datetimepicker实例,再调用显示方法:
const pickerInstance = document.getElementById('id_basefield').datetimepicker; pickerInstance.show();
额外注意事项
- 你的代码中
data-toggle属性值为datetimepickerv,多了末尾的v,这可能导致点击日历图标也无法正常触发,建议修正为data-toggle="datetimepicker"。 - 需确保页面已正确引入Bootstrap datetimepicker的CSS和JS文件,且插件已完成初始化。
内容的提问来源于stack exchange,提问作者Jason Howard
相关产品推荐
相关产品推荐

