如何延迟,当用户键入按键preSS功能,因此它不会触发针对每个按键的请求?按键、功能、用户、preSS

2023-09-10 16:06:26 作者:別捅了俄①刀還問俄疼不疼

背景

我有一些页面上的下拉菜单中。如果你改变了第一个,在下拉列表的其余部分,根据您选择什么更新。

I have a number of dropdowns on a page. If you change the first one, the rest of the dropdowns are updated according to what you've selected.

在我们的例子中,我们处理基金数据。因此,第一个下拉列表是所有的基金类型。您可以选择对冲基金,下一个下拉列表是通过选择仅适用于对冲基金进行过滤。

In our case, we deal with fund data. So the first dropdown is "All Fund Types". You select "Hedge Funds", and the next dropdown is filtered by options that only apply to Hedge Funds.

客户端现在要我把一个文本框到组合,其中当用户开始打字,会影响这些结果。

The client is now asking me to put a text field into the mix, which when the user starts typing, will effect those results.

因此​​,如果他们输入美元,第二个下拉将只包含有基金名称中美元选项。

So if they type "USD", the second dropdown will only contain options that have funds with "USD" in the name.

问题

这是我遇到的具体问题是,与code我使用:

The specific problem that I'm having is that with the code I'm using:

$('#Search').keypress(function () {
    // trigger the updating process
});

它引发了搜索每个按键preSS。所以,当我输入USD我立刻得到3请求 - 一个是U,一为美国,一个是美元

It's triggering the search for each key press. So when I type "USD" I'm getting 3 requests immediately - one for "U", one for "US" and one for "USD".

我已经尝试设置超时与此:

I've tried setting a timeout with this:

$('#Search').keypress(function () { 
    // I figure 2 seconds is enough to type something meaningful
    setTimeout(getFilteredResultCount(), 2000);
});

但所有这确实是间隔2秒做什么,我描述了。

but all that does is wait 2 seconds before doing what I've described.

我敢肯定,这个问题已经被解决。可能有人建议如何解决这个问题呢?

I'm sure this problem has been solved before. Could somebody suggest how to solve this issue?

推荐答案

我的方式这样做之前是设置一个超时,但每次一个新的关键是pressed清除现有超时。这样,你应该只得到请求,当用户有被发送的停止的打字。

The way I have done this before is to set a timeout, but clear the existing timeout each time a new key is pressed. That way you should only get the request being sent when the user has stopped typing.

var timeoutId = 0;
$('#Search').keypress(function () { 
    clearTimeout(timeoutId); // doesn't matter if it's 0
    timeoutId = setTimeout(getFilteredResultCount, 500);
    // Note: when passing a function to setTimeout, just pass the function name.
    // If you call the function, like: getFilteredResultCount(), it will execute immediately.
});

(我会去约500毫秒超时。)

(I'd go for about 500ms timeout.)