jQuery Datepicker onchange事件问题

贝斯特宙斯

我有一个JS代码,当您更改字段时,它会调用搜索例程。问题是当Datepicker更新输入字段时,我找不到将触发的jQuery事件。

由于某些原因,当Datepicker更新该字段时,不会调用change事件。当日历弹出时,它会改变焦点,所以我也不能使用它。有任何想法吗?

TJ人群

您可以使用datepicker的onSelectevent

$(".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是,即使选择了某个日期,也不会触发它。这是datepicker中的一个设计缺陷:它始终会触发onSelect(即使没有任何更改),也不会在更改的基础输入上触发任何事件。(如果您查看该示例的代码,则我们正在侦听更改,但未提出更改。)当事情发生更改时,它可能应该在输入上触发一个事件(可能是通常的change事件,或者可能是日期选择器-具体的一个)。


当然,如果您愿意,可以将change事件input设为火上浇油:

$(".date").datepicker({
    onSelect: function() {
        $(this).change();
    }
});

对于通过jQuery连接的任何处理程序,这都会change在底层触发input但是,它总是会触发它。如果您只想进行实际更改,则必须保存先前的值(可能通过data)并进行比较。

现场示例

$(".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>

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章