我有与KnockoutJS集成的jQuery UI datepicker。
<input class="input-small hasDatepicker" data-bind="datepicker: ItemCurrentDate, datepickerOptions: { dateFormat: 'dd/mm/yy', changeMonth: true, changeYear: true, minDate: ItemStartDate(), maxDate: ItemEndDate(), datePickerPlaceholder: 'dd/mm/yy' } name="ItemCurrentDate" type="text" value="" placeholder="dd/mm/yy" id="dp12345">
我不得不添加minDate和maxDate限制。 添加minDate限制后,它将当前值(ItemCurrentDate)设置为maxDate值,即使ItemCurrentDate&gt; = ItemStartDate也是如此。 当我打开dp时,我需要ItemStartDate保持不变。
答案 0 :(得分:0)
并非完全遵循这个问题,但这会有效吗?这是一个小提琴。 http://jsfiddle.net/LkqTU/33447/我不能确定你的问题是否最小和最大日期是可以改变的可观测量。我认为它们是静态的,但如果不是,您可能需要更改自定义绑定的更新部分,可能会破坏日期选择器并使用新的最小和最大日期重新创建它。
您可以运行下面的解决方案,也可以使用上面提到的小提琴
ko.bindingHandlers.datepicker = {
init: function(element, valueAccessor, allBindingsAccessor) {
var options = allBindingsAccessor().datePickeroptions || {};
options.onSelect = function(selected, evnt) {
var observable = valueAccessor();
observable(selected);
};
$(element).datepicker(options);
// setting initial value
$(element).datepicker("setDate", valueAccessor()());
//handle disposal (if KO removes by the template binding)
ko.utils.domNodeDisposal.addDisposeCallback(element, function() {
$(element).datepicker("destroy");
});
},
//update the control when the view model changes
update: function(element, valueAccessor, allBindingsAccessor) {
var value = ko.utils.unwrapObservable(valueAccessor());
$(element).datepicker("setDate", valueAccessor()());
}
};
function model() {
var self = this;
this.itemCurrentDate = ko.observable(new Date(2017, 1, 26));
this.itemStartDate = ko.observable(new Date(2017, 1, 1));
this.itemEndDate = ko.observable(new Date(2017, 2, 22));
this.resetDate = function() {
self.itemCurrentDate(new Date(2017, 1, 26));
}
}
var mymodel = new model();
$(document).ready(function() {
ko.applyBindings(mymodel);
});
&#13;
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.2.0/knockout-min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.12.1/jquery-ui.min.js"></script>
<link href="https://ajax.googleapis.com/ajax/libs/jqueryui/1.12.1/themes/smoothness/jquery-ui.css" rel="stylesheet" />
<input data-bind="datepicker: itemCurrentDate,
datePickeroptions: {
dateFormat: 'dd/mm/yy',
changeMonth: true,
changeYear: true,
minDate: itemStartDate(),
maxDate: itemEndDate(),
datePickerPlaceholder: 'dd/mm/yy'
}
" />
<p>
theDate: <span data-bind="text: itemCurrentDate"></span>
</p>
<p>
<input type="button" data-bind="click: resetDate" value="reset date" </p>
</p>
&#13;