没改样式,功能不齐全,用的百度的接口
传参的类型要对应百度给的。适合ajax新手拿去练手。
<div class="box">
<input type="text" id="tex" name="wd">
<input type="button" id="btn" value='搜索'>
<div class="inner"></div>
</div>
js部分
$('#tex').keyup(function(){
// console.log(1);
var te = $('#tex').val();
$.ajax({
url:'https://sp0.baidu.com/5a1Fazu8AA54nxGko9WTAnF6hhy/su',
jsonp:'cb',
data:{wd:te},
dataType:'jsonp',
success:function(data){
console.log(data.s);
var content="",a;
for(a = 0;a<data.s.length;a++){
content += '<ul>'+
'<li>'+data.s[a]+'</li>'+
'</ul>'
}
$('.inner').css({
display:'block'
})
$('.inner').html(content);
$('.inner').find('li').hover(function(){
$(this).css({
backgroundColor:'red'
})
},function(){
$(this).css({
backgroundColor:'#fff'
})
})
}
})
$('#btn').click(function(){
location.href = "http://www.baidu.com/s?wd=" + te;
})
$('.inner').delegate('li','click',function(){ //事件代理
var liTex = $(this).text();
window.location.href = "http://www.baidu.com/s?wd=" + liTex;
})
})
其实要注意的就是事件代理这块,因为动态生成的li,没办法去绑定,所以代理给父元素。
实现的就是点击li,跳到对应的搜索结果。