我在页面上有几个flatpickr输入,它们都有class ='flatpickr'。当用户从输入中手动删除日期时,我想调用clear方法。使用以下事件处理程序访问实际的flatpickr实例的语法是什么?
<input id="OpenDate" name="OpenDate" type="text" v-model="Item.OpenDate" class="form-control form-control-sm flatpickr" />
$('.flatpickr').change(function () {
console.log(this); // html input control
console.log($(this)); // jquery object instance
// flatpickr instance ???
// if (value == '')
// ???.clear();
});
答案 0 :(得分:0)
问题在于,当您从flatpickr.clear()
事件中调用change
函数时,会导致无限循环(因为clear
函数也调用change
事件)。
我的解决方法是使用标志shouldClear
并将其设置在需要清除的元素上:
flatpickr(".flatpickr",{dateFormat: "M d, Y", allowInput: true });
$(".flatpickr").on('input', function(e) {
if(!this.shouldClear && !this.value.length && this._flatpickr.currentYear ) {
this.shouldClear = true;
this._flatpickr.clear();
this.shouldClear = false;
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/flatpickr/dist/flatpickr.min.css">
<script src="https://cdn.jsdelivr.net/npm/flatpickr"></script>
<input id="OpenDate1" name="OpenDate" type="text" class="form-control form-control-sm flatpickr" autocomplete="off" />
<input id="OpenDate2" name="OpenDate" type="text" class="form-control form-control-sm flatpickr" />
<input id="OpenDate3" name="OpenDate" type="text" class="form-control form-control-sm flatpickr" />