问题描述
我有一个JS代码,当您更改字段时,它会调用搜索例程.问题是当Datepicker更新输入字段时,我找不到任何会触发的jQuery事件.
I have a JS code in which when you change a field it calls a search routine. The problem is that I can't find any jQuery events that will fire when the Datepicker updates the input field.
由于某些原因,当Datepicker更新该字段时,不会调用change事件.当日历弹出时,它会更改焦点,所以我也不能使用它.有什么想法吗?
For some reason, a change event is not called when Datepicker updates the field. When the calendar pops up it changes the focus so I can't use that either. Any ideas?
推荐答案
您可以使用日期选择器的 onSelect
事件.
You can use the datepicker's onSelect
event.
$(".date").datepicker({
onSelect: function(dateText) {
console.log("Selected date: " + dateText + "; input's current value: " + this.value);
}
});
实时示例:
$(".date")
.datepicker({
onSelect: function(dateText) {
console.log("Selected date: " + dateText + "; input's current value: " + this.value);
}
})
.on("change", function() {
console.log("Got change event from field");
});
<link href="http://code.jquery.com/ui/1.9.2/themes/smoothness/jquery-ui.css" rel="stylesheet" />
<input type='text' class='date'>
<script src="http://code.jquery.com/jquery-1.8.3.min.js"></script>
<script src="http://code.jquery.com/ui/1.9.2/jquery-ui.js"></script>
不幸的是,无论何时选择日期,onSelect
都会触发,即使它没有更改.这是日期选择器中的一个设计缺陷:它始终会触发onSelect
(即使未进行任何更改),并且不会在更改的基础输入上触发任何事件. (如果您查看该示例的代码,我们正在侦听更改,但未提出更改.)当事情发生更改时,它可能应该在输入上触发一个事件(可能是通常的change
事件,或者可能是日期选择器专用的).
Unfortunately, onSelect
fires whenever a date is selected, even if it hasn't changed. This is a design flaw in the datepicker: It always fires onSelect
(even if nothing changed), and doesn't fire any event on the underlying input on change. (If you look in the code of that example, we're listening for changes, but they aren't being raised.) It should probably fire an event on the input when things change (possibly the usual change
event, or possibly a datepicker-specific one).
当然,如果愿意,可以在input
火上触发change
事件:
If you like, of course, you can make the change
event on the input
fire:
$(".date").datepicker({
onSelect: function() {
$(this).change();
}
});
对于通过jQuery连接的任何处理程序,将在基础input
上触发change
.但同样,它会总是触发它.如果您只想触发实际更改,则必须保存先前的值(可能通过data
)并进行比较.
That will fire change
on the underlying input
for any handler hooked up via jQuery. But again, it always fires it. If you want to only fire on a real change, you'll have to save the previous value (possibly via data
) and compare.
实时示例:
$(".date")
.datepicker({
onSelect: function(dateText) {
console.log("Selected date: " + dateText + "; input's current value: " + this.value);
$(this).change();
}
})
.on("change", function() {
console.log("Got change event from field");
});
<link href="http://code.jquery.com/ui/1.9.2/themes/smoothness/jquery-ui.css" rel="stylesheet" />
<input type='text' class='date'>
<script src="http://code.jquery.com/jquery-1.8.3.min.js"></script>
<script src="http://code.jquery.com/ui/1.9.2/jquery-ui.js"></script>
这篇关于jQuery Datepicker onchange事件问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!