javascript - 创建搜索时候如何根据输入实时显示输出。
高洛峰
高洛峰 2017-04-10 14:53:45
[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.

高洛峰
高洛峰

拥有18年软件开发和IT教学经验。曾任多家上市公司技术总监、架构师、项目经理、高级软件工程师等职务。 网络人气名人讲师,...

全部回复(3)
阿神
//使用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);
});
高洛峰

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

迷茫

用Ajax做

热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责申明 举报中心 意见反馈 讲师合作 广告合作 最新更新
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送

Copyright 2014-2026 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号