簡體   English   中英

是否有可能/如何像 Google 插件一樣為 jQuery 自動完成設置延遲?

[英]Is it possible / How to set a delay for jQuery Autocomplete like Google plugin?

我正在使用像 Google 一樣的 jQuery 插件Autocomplete ,它運行良好。 但是每次按鍵都會觸發 AJAX 請求。 這意味着,字符串washington將導致十個(!)請求。 好吧,可以通過使用選項minLength減少請求的數量。 但是例如使用minLength:3我們仍然發送七個請求(從第四個字符開始)。

$(function() {
    $("#bar").autocomplete({
        minLength: 3,
        limit: 5,
        source : [
            function(query, add) {
                fooNumber = $('#foo-number').val();
                $.getJSON("/my/ajax/controller/bar?data[number]=" + query + "&data[foo_name]=" + fooNumber, function(response) {
                    add(response);
                })
        }],  
    });
});

當用戶自例如300 ms以來沒有打字時,如何防止即時請求服務器並使腳本僅發送新請求?

這可能有用。 (未測試)

//global variable
var keyPressed = new Date();
// Call where you're watching for pressed keys.
var updateKeyPressed = function(){
    keyPressed = new Date();
}

$(function() {
    $("#bar").autocomplete({
        minLength: 3,
        limit: 5,
        appendMethod:'replace',
        closeOnBlur: true,
        source : [
            function(query, add) {
                var currentDate = new Date();
                setInterval(function(){
                    currentDate = new Date();
                    if (currentDate.getTime() > keyPressed.getTime()) {
                        orderApplicationNumber = $('#foo-number').val();
                        $.getJSON("/my/ajax/controller/bar?data[number]=" + query + "&data[foo_name]=" + fooNumber, function(response) {
                            add(response);
                        });
                    }
                }, 300);
            }
        ],
    });
});

對不起,我誤會了。 您可以使用源代碼中的函數對標志和 settimeout 執行一些邏輯,例如(尚未對其進行測試):

無功定時器;

$("#bar").autocomplete({
        minLength: 3,
        limit: 5,
        cacheLength: 1,
        source : [
            function(query, add) {

                clearTimeout(timer);

                timer = setTimeout(function(){

                    fooNumber = $('#foo-number').val();
                    $.getJSON("/my/ajax/controller/bar?data[number]=" + query + "&data[foo_name]=" + fooNumber, function(response) {
                        add(response);
                    })

                }, 300)

        }],
    });

或者你可以切換到 jquery ui >

原答案:

jquery ui 自動完成有一個內置參數,延遲DOCS

從文檔:

$( ".selector" ).autocomplete({
  delay: 500
});

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM