首页 > 解决方案 > 我可以使用 javascript 变量在 jQuery Datepicker 上设置 yearRange 吗?

问题描述

我需要从两个javascript变量中设置yearRange,但是这些变量仅在用户从页面上的多个按钮中选择一个之后才设置,每个按钮都将变量设置为特定年份,因此当用户加载页面时变量获胜'不是已经设置好了。我不知道我想要的是否可能,因为我不确定变量的值是否会更新。我认为代码应该类似于:

var startDate;
var endDate;

$(".pickdate").datepicker({
 showOn: 'focus',
 yearRange: startDate+':'+endDate,
 changeMonth: true,
});

其中变量的值是从另一个 .js 文件中获取的。

标签: javascriptjquerydatepicker

解决方案


是的,如果您在此处提到的代码之前在全局范围内加载了第二个 js,则可以。


[更新] 片段示例:正如您在此示例中看到的,您不能选择 2021 年之后或 2018 年之前的日期!这就是该yearRange选项的目的。它应该为日历定义设置限制。

console.log(dates.enddate);
$(".pickdate").datepicker({
 showOn: 'focus',
 yearRange: dates.startDate+':'+dates.enddate,
 changeMonth: true,
});

//If already contactenated, We can write:
//yearRange: range,
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="//code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
<!doctype html>

<html lang="en">
<head>
  <meta charset="utf-8">

  <title>Datepicker</title>

  <link rel="stylesheet" href="https://code.jquery.com/ui/1.12.0/themes/smoothness/jquery-ui.css">
  <script>var dates={ startDate:"2018",enddate:"2021"};
  //var range = dates.startDate+':'+dates.enddate;
  </script>

</head>

<body>
  <div class="pickdate"></div>
</body>
</html>


例子:

    //settings.js
var dates={ startDate:"2018",enddate:"2021"}

因此,您只需在脚本之前加载它,如下所示:

    <script src="settings.js"></script> 
    //Your code comes after

$(".pickdate").datepicker({
 showOn: 'focus',
 yearRange: dates.startDate+':'+dates.endDate,
 changeMonth: true,
});

有关相对默认值等其他详细信息,您可以遵循Datepicker Widget的指南


推荐阅读