ホームページ  >  に質問  >  本文

javascript - 创建搜索时候如何根据输入实时显示输出。

If you were building a search tool and wanted search results to pop up as you typed, write a function that gets called on every key down but calls the server when the user stops typing for 400ms.

高洛峰高洛峰2722日前438

全員に返信(4)返信します

  • 阿神

    阿神2017-04-10 14:55:45

    //使用jquery编写...
    
    var delay = null;
    
    $('#searchInput').on('keyup', function () {
    
        if(delay) {
            clearTimeout(delay);
        }
    
        //判断文字内容长度是否达到最低要求
        var searchKey = $(this).val();
        if (searchKey.length < 2) { return; } 
    
        //延迟查询api
        delay = setTimeout(function () {
            $.get('/api/search', {searchKey: searchKey}).then(function (data) {
              //填充数据....
              doSomething(data);
    
              //显示结果列表
              $('#result-list').show();
            });
        }, 400);
    });
    

    返事
    0
  • 高洛峰

    高洛峰2017-04-10 14:55:45

    监听事件 -> 读前端cache ? 构建结果列表 : (发请求拿结果 -> cache并构建结果列表)
    400ms 可以用计时器做 delay 处理,根据事件触发情况看是进后面流程还是 clear 掉。

    返事
    0
  • 迷茫

    迷茫2017-04-10 14:55:45

    哈,我也搞過這種東西,處理辦法也是同樣的。

    之所以這樣,是因爲你會發現在用戶高速鍵入的時候發出的請求很多,卻只有最後一個纔有意義。況且實時感也只是在你停頓的時候才能顯現出來。

    所以這一 debounce 可以很有效地改善體驗。

    具體實現,除了 debounce 就是 ajax,隨便找個庫比如 underscore 都會提供。

    原理如樓上代碼,就是對每次事件先 clearTimeout 再 setTimeout。

    http://www.glassdoor.com/Interview/If-you-were-building-a-search-tool-and-wanted-search-results-to-pop-up-as-you-typed-but-the-server-call-was-taxing-write-a-QTN_835901.htm

    返事
    0
  • 迷茫

    迷茫2017-04-10 14:55:45

    用Ajax做

    返事
    0
  • キャンセル返事