在 flatpickr 更改事件中清除日期

Clear date in flatpickr change event

我在一个页面上有几个 flatpickr 输入,它们都有 class='flatpickr'。当用户从输入中手动删除日期时,我想调用清除方法。使用以下事件处理程序访问实际的 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();
});

问题是,当您从 change 事件中调用 flatpickr.clear() 函数时,它会导致无限循环(因为 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"  />