有条件的反跳,具体取决于event.keyCode [英] Conditional debounce, depending on event.keyCode

查看:64
本文介绍了有条件的反跳,具体取决于event.keyCode的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个搜索字段,它接受用户输入并使用去抖动的事件侦听器发出ajax请求.

I have a search field that takes user input and makes ajax requests using a debounced event listener.

html:

<input id="search" type="text"></input>

javascript:

javascript:

function makeRequest() {
  // make ajax request, do things with the information
}

$('#search').on('keypress', _.debounce(makeRequest, 200));

我需要事件监听器使用上下箭头上的去抖动的ajax函数,即event.keyCode === 38event.keyCode === 40

I need the event listener to not use the debounced ajax function on arrow up and down, that is event.keyCode === 38 or event.keyCode === 40

是否可以应用

Is there a way to apply the advice from this question to my problem?

推荐答案

问题是事件监听器的回调需要调用从_.debounce返回的函数,而不仅仅是创建去抖动的函数.

The problem was that the callback to the event listener needs to call the function returned from _.debounce, not just create the debounced function.

$('#search').on('keypress', function(event) {
  if (event.which === 38 || event.which === 40) {
    // do other things
    return;
  }
  _.debounce(makeRequest, 200)();
});

这篇关于有条件的反跳,具体取决于event.keyCode的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆