当前位置: 移动技术网 > IT编程>开发语言>JavaScript > jsonp实现百度下拉框功能的方法分析

jsonp实现百度下拉框功能的方法分析

2019年07月21日  | 移动技术网IT编程  | 我要评论

本文实例讲述了jsonp实现百度下拉框功能的方法。分享给大家供大家参考,具体如下:

思路就是获取用户输入,然后根据用户输入调用百度的一个接口jsonp实现跨域请求,然后将百度返回给的内容渲染数据到视图。需要注意的就是,发送请求的时候记得编码用户输入的内容

var obj=document.queryselector('#user-input');
var body=document.queryselectorall('body')[0];
var ul=document.queryselector('#ul');
var inner='';
function render(data){
    //删除前一次请求的li的内容
    if(ul.innerhtml!=''){
      ul.innerhtml='';
    }
    for(let i = 0, length1 = data.s.length; i < length1; i++){
      var li=document.createelement('li');
      li.innerhtml=data.s[i];
      ul.appendchild(li);
    }
}
obj.addeventlistener('keyup',function(){
    if(document.queryselector('#request')){
      body.removechild(document.queryselector('#request'));
    }
      var script=document.createelement('script');
      script.id="request";
      script.src="http://unionsug.baidu.com/su?wd="+encodeuri(obj.value.trim())+'&p=3&cb=render';
      body.appendchild(script);
});
//利用冒泡添加事件。
ul.addeventlistener('click',function(e){
    var e=e||window.event;
    window.location.href="https://www.baidu.com/s?word=" rel="external nofollow" +encodeuri(e.target.innerhtml);
});

<style type="text/css">
  *{
          margin: 0;
          padding: 0;
  }
  ul{
          margin-left: 10px;
          transition: all 1s ease;
  }
    input{
          width: 300px;
          height: 40px;
          line-height: 40px;
          background: #4caf50a6;
          outline: none;
          border: none;
          border-radius: 10px;
          padding-left: 15px;
          color: white;
          font-size: 20px;
    }
    li{
          cursor: pointer;
          transition: all 1s ease;
          list-style: none;
          width: 280px;
          height: 30px;
          line-height: 30px;
          background: #8acb8da8;
          color: #888e4a;
          padding-left: 10px;
    }
    li:hover{
          background: #64a968;
          color: #caf1cc;
    }
    input::-webkit-input-placeholder{
      color:white;
    }
    input::-moz-placeholder{  /* mozilla firefox 19+ */
      color:white;
    }
    input:-moz-placeholder{  /* mozilla firefox 4 to 18 */
      color:white;
    }
    input:-ms-input-placeholder{ /* internet explorer 10-11 */ 
      color:white;
    }
</style>

更多关于javascript相关内容感兴趣的读者可查看本站专题:《javascript操作dom技巧总结》、《javascript页面元素操作技巧总结》、《javascript事件相关操作与技巧大全》、《javascript查找算法技巧总结》、《javascript数据结构与算法技巧总结》、《javascript遍历算法与技巧总结》及《javascript错误与调试技巧总结

希望本文所述对大家javascript程序设计有所帮助。

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网