jQuery.inArray() 函数在 jQuery-ui DatePicker 的 beforeShowDay 函数中无法正常工作

jQuery.inArray() function doesn't work correctly in beforeShowDay function of jQuery-ui DatePicker

我尝试通过更改 class 来突出显示保存在数据库中的一组日期。为了这个目标,我使用了 beforeShowDay 函数,并且我已经尝试了 Stack Overflow 上的所有解决方案。甚至其中一些看起来很合乎逻辑,每次都会出错。

我使用Laravel和jQuery来完成目标。我还使用 jQuery-ui DatePicker.

的 multiDatesPicker 扩展

这是我的输入字段:

<input required type="text" name="dates" id="datepicker" class="form-control">

我的脚本:

$(document).ready(function() {

  var openDates = @json($open_dates);

  $( "#datepicker" ).multiDatesPicker({
     beforeShowDay: function (date) {
       if ($.inArray(date, openDates) !== -1) {
           return [true, 'open-date'];
       }else {
           return [true, ''];
       }
     }
  });
});

以及控制器中的代码

$open_dates_raw = ExcursionDate::where('excursion_id', $excursion->id)->get();
$open_dates = array();
foreach ($open_dates_raw as $d) {
  $open_dates[] = $d->date; /*It is a DATE, not DATETIME column*/
}

return view("view.name", [
                   ...
                   'open_dates' => $open_dates,
                   ... ]);

基本上,我认为 $.inArray(date, openDates) 中的某些内容不起作用,因为我尝试了很多不同的选项,但仍然找不到匹配项.

当我在 beforeShowDay 中 console.log date 变量时,我得到这个:

...
Tue Mar 30 2021 00:00:00 GMT+0300 (EEST)
...

当我 console.log openDates 变量时,它显示一个如下所示的数组:

(4) ["2021-03-10 00:00:00", "2021-03-17 00:00:00", "2021-03-24 00:00:00", "2021-03-31 00:00:00"]

我也尝试操纵控制器的输出:

(4) ["2021-03-10 ", "2021-03-17", "2021-03-24", "2021-03-31"]

甚至这样:

(4) ["2021-3-10 ", "2021-3-17", "2021-3-24", "2021-3-31"]

所以现在回到脚本 - 我尝试了不同的选项,例如

if ($.inArray(date.toString(), openDates) !== -1)

甚至

if ($.inArray(openDates, date) !== -1)

我也试过更换控制器:

$open_dates = ExcursionDate::where('excursion_id', $excursion->id)->pluck('date');

但还是没有...

有什么想法吗?

我不知道你的 openDates 的确切格式,但我知道里面的值是字符串,所以我将日期转换为字符串,如下所示:

  beforeShowDay: function(date) {
    var str_date = $.datepicker.formatDate( "yy-mm-dd", date);
    //console.log(str_date);
    if ($.inArray(str_date, openDates) !== -1) {
      return [true, 'open-date'];
    } else {
      return [true, ''];
    }
  }

您可以按照 openDates 中的日期格式更改格式