这篇文章将为大家详细讲解有关使用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, length2 = data.s.length; i < length2; 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>
关于使用jsonp怎么实现一个百度下拉框功能就分享到这里了,希望以上内容可以对大家有一定的帮助,可以学到更多知识。如果觉得文章不错,可以把它分享出去让更多的人看到。
亿速云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。