实现原理很简单,代码如下:

<!DOCTYPE html>
<html>
 <head> 
  <meta charset="UTF-8"> 
  <title>input输入框实现联想关键词功能</title> 
  <script src="http://www.kiscms.com/static/jquery-3.1.1.min.js"></script> 
 </head> 
 <body> 
  <input type="text" id="keyword"> 
  <script type="text/javascript">
    var input = $("#keyword");
    input.keyup(function() {
        var curKeyword = input.val();
        console.log('send: '+curKeyword);
    });
  </script>  
 </body>
</html>

但是上面这个代码有瑕疵,用户在连续输入的过程中,每一次onkeyup都会发起一次请求,这样对服务器的压力很大,需要做优化。

利用javascript的闭包特性可以做到,当用户输入结束后才会发起请求,优化后的代码如下:

<!DOCTYPE html>
<html>
 <head> 
  <meta charset="UTF-8"> 
  <title>input输入框实现联想关键词功能</title> 
  <script src="http://www.kiscms.com/static/jquery-3.1.1.min.js"></script> 
 </head> 
 <body> 
  <input type="text" id="keyword"> 
  <script type="text/javascript">
    var input = $("#keyword");
    var lastKeyword = '';
    input.keyup(function() {
        var curKeyword = input.val();
        lastKeyword = curKeyword;
        setTimeout(function() {
            console.log('lastKeyword: '+lastKeyword+' curKeyword: '+ curKeyword);
            if(lastKeyword == curKeyword && curKeyword != '') {
                console.log('send: '+curKeyword);
            }
        }, 500);
    });
  </script>  
 </body>
</html>

 

个人公众号谢谢各位老铁支持

input输入框实现联想关键词功能

 

QQ群:   281442983 (点击链接加入群:http://jq.qq.com/?_wv=1027&k=29LoD19) 

 

我的淘宝店,可以进去逛逛噢:https://shop108912636.taobao.com/index.htm?spm=2013.1.w5001-7867000954.3.1d29318dPlLar7&scene=taobao_shop

 

相关文章:

  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2022-01-11
  • 2021-10-06
  • 2021-08-26
  • 2022-12-23
  • 2022-12-23
猜你喜欢
  • 2022-01-27
  • 2021-12-31
  • 2022-12-23
  • 2022-01-03
  • 2022-12-23
  • 2022-12-23
相关资源
相似解决方案