jquery - JQuery 在更改和延迟时运行功能
问题描述
我发现这个函数可以延迟 keyup 回调,在我设置它的 3 秒后它也能正常工作。
function delay_callback(callback, ms) {
var timer = 0;
return function() {
var context = this, args = arguments;
clearTimeout(timer);
timer = setTimeout(function () {
callback.apply(context, args);
}, ms || 0);
};
}
$('#postcode').keyup(delay_callback(function (e) {
do_postcode();
validate_fields();
}, 3000));
所以我也想像这样在更改时调用它,$('#postcode').on('change',...
但是除了延迟之外,它还使它在更改时运行,然后在 3 秒后运行,所以它运行了两次。
我的“onchange”代码
$('#postcode').on('change', function(e) {
e.stopPropagation();
do_postcode();
validate_fields();
});
如何在更改时和延迟后调用该函数,但不能同时调用。
所以我想在输入改变时取消延迟
解决方案
如果我理解您的解释,您想捕获这两个事件,但您只想在检测到事件更改时取消延迟..
timer = -1;
function delay_callback(callback, ms) {
return function() {
var context = this, args = arguments;
timer = setTimeout(function () {
callback.apply(context, args);
}, ms || 0);
};
}
$('#postcode').keyup(delay_callback(function (e) {
do_postcode();
validate_fields();
}, 3000));
$('#postcode').on('change', function(e) {
clearTimeout(timer);
do_postcode();
validate_fields();
});
为什么不用输入事件替换 keyup 事件?
$('#postcode').on("input change", function (e) {
var $this = $(this);
if(e.type == "change"){
clearTimeout($this.data('timer'));//if you want to cancel the timeout
do_postcode();
validate_fields();
return;
}
var delay = 3000; // 3 seconds delay after last input
clearTimeout($this.data('timer'));
$this.data('timer', setTimeout(function(){
do_postcode();
validate_fields();
}, delay));
});
推荐阅读
- image - 从不以 .jpeg 结尾的 URL 下载图像
- string - 如何将字符串列表拆分为列表中的字符串列表?
- c - 阶乘函数只数到 12
- git - 将提交移动到 Visual Studio 中的不同分支?
- reactjs - 寻找如何使用 React i18n 的确认
- regex - 仅在具有特定前缀的文件中搜索 IntelliJ 中的文本
- azure-devops - 发出会话令牌时出错:HostAuthorizationNotFound
- django - Django Rest Framework 分页和过滤
- ansible - 如果标准输出结果等于失败,如何使用 Ansible 重新启动服务器?
- filesystems - MTDBLOCK1 似乎被嵌入式 Linux 系统上的 SD 卡内容覆盖