如何在jQuery中突出显示日期?

时间:2018-01-27 13:29:17

标签: c# jquery asp.net-mvc jquery-ui razor

我无法动态突出显示日历中的日期,只有静态日期会突出显示:

eventDates[new Date('01/09/2018')] = new Date('01/09/2018')

这是我的代码:

$(function() {
  // An array of dates
  var eventDates = [];
  $.ajax({
    type: "GET",
    url: "@Url.Action("
    GetEvents ", "
    Home ")",
    dataType: "json",
    data: "",
    success: function(data) {
      $.each(data, function(i, val) {
        var dd = CTD(val.Date); //CTD means convert into date 
        eventDates[i] = dd;
      });
    }
  });
  // convert in date
  function CTD(d) {
    var date = new Date(parseInt(d.substr(6)));
    var month = date.getMonth() + 1;
    return date.getDate() + "/" + month + "/" + date.getFullYear();
  }

  //eventDates[new Date('01/09/2018')] = new Date('01/09/2018');

  // datepicker
  $('#datepicker').datepicker({
    beforeShowDay: function(date) {
      var highlight = eventDates[date];
      if (highlight) {
        return [true, "event", 'Tooltip text'];
      } else {
        return [true, '', ''];
      }
    }
  });
});

1 个答案:

答案 0 :(得分:0)

然后在DatePicker中,您正在搜索数组索引,因此您将找不到日期。要查找您需要使用indexOf()方法的日期,您需要使用您在数组中保存的相同格式设置DatePicker日期的格式:

var month = date.getMonth() + 1;
date = date.getDate() + "/" + month + "/" + date.getFullYear();
var highlight = eventDates.indexOf(date);

您可以将CTD()函数中的格式代码提取到新函数中,而不是重复代码来格式化日期:

// convert in date
function CTD(d) {
  var date = new Date(parseInt(d.substr(6)));
  return FD(date);
}
// format date
function FD(d) {
  return d.getDate() + "/" + (d.getMonth() + 1) + "/" + d.getFullYear();
}

最后,你想确保DatePicker的代码只在Ajax结果返回后运行,所以放入一个函数并从Ajax的success调用它:

$(function() {
  $.ajax({
    type: "GET",
    url: "@Url.Action("GetEvents", "Home")",
    dataType: "json",
    data: "",
    success: function(data) {
      var eventDates = []; //An array of dates
      $.each(data, function(i, val) {
        eventDates[i] = CTD(val.Date); //CTD means convert into date 
      });
      HighlighEvents(eventDates);
    }
  });
  // convert in date
  function CTD(d) {
    var date = new Date(parseInt(d.substr(6)));
    return FD(date);
  }
  // format date
  function FD(d) {
    return d.getDate() + "/" + (d.getMonth() + 1) + "/" + d.getFullYear();
  }
  // datepicker
  function HighlighEvents(eventDates) {
    $('#datepicker').datepicker({
      beforeShowDay: function(date) {
        var highlight = eventDates.indexOf(FD(date));
        if (highlight > -1) {
          return [true, "event", 'Tooltip text'];
        } else {
          return [true, '', ''];
        }
      }
    });
  }
});