代码之家  ›  专栏  ›  技术社区  ›  Chris

使用JSON文件禁用JQuery UI日期选择器中的日期

  •  2
  • Chris  · 技术社区  · 12 年前

    我是一名学徒,刚接触编程,我对J-Query、JavaScript等知之甚少。我正在创建一个程序,用户可以使用 datepicker 。我希望在日期选择器中禁用所有英国银行假日。我有一个 JSON file from the government website 其中包含我希望禁用的所有天数和其他数据。我希望它们像周末一样被禁用,而当前在日期选择器中被禁用。

    function IsWeekend(date) {
    if (date.getDay() === 0 || date.getDay() === 6) return true;
    else return false;
    }
    
    $(function () {
        $(".datepicker").datepicker({
            minDate: ('+1d'),
            dateFormat: 'dd/mm/yy',
            beforeShowDay: function (date) {
                return [(!IsWeekend(date))];
            }
        });
    });
    

    JSON文件的格式如下

    {"england-and-wales":{"division":"england-and-wales","events":[{"title":"New Year\u2019s Day","date":"2012-01-02","notes":"Substitute day","bunting":true},
    {"title":"Good Friday","date":"2012-04-06","notes":"","bunting":false}
    
    1 回复  |  直到 12 年前
        1
  •  1
  •   Shiva    12 年前

    解决方案是,我们首先需要读取json文件并加载它以提取要禁用的日期。

    由于AJAX调用无法远程进行 同源保单 您必须将内容复制到本地JSON文件中。

    然后我们将穿越 英格兰和威尔士 索引,因为我们只关注这里的日期,并创建一个数组,只需额外检查一下,如果这个数组中存在周末或日期,我们将禁用它。

    所以JavaScript代码将是一些东西。

    var holidayDates = new Array(); // this array will store the holiday dates after being extracted form the JSON
         $.ajax({
           url: 'json/bank-holiday.json',// change the link to your local copy
           method: 'GET',
           dataType: 'json',
           success: function(data) {
             // now the data is loaded and we will traverse over the "england-and-wale" 's events and create an array to of dates of holidays
             var listOfEvents = data['england-and-wales'].events;
             for (var i in listOfEvents) {
               holidayDates.push(listOfEvents[i].date);// push the date to our array for checking afterwards
             }
    
           }
         });
    
         function IsWeekend(date) {
           if (date.getDay() === 0 || date.getDay() === 6) return true;
           else return false;
         }
    
          $(function() {
           $(".datepicker").datepicker({
             minDate: ('+1d'),
             dateFormat: 'dd/mm/yy',
             beforeShowDay: function(date) {
               var string = jQuery.datepicker.formatDate('yy-mm-dd', date);
               var isDisabled = (!IsWeekend(date)) && (holidayDates.indexOf(string) == -1); // used to disable if its an holiday or weekend
               return [isDisabled];
             }
           });
         });
    

    我还创建了一个工作样本,您可以找到 here

    推荐文章