jquery中用jsonp实现搜索框功能

没改样式,功能不齐全,用的百度的接口
传参的类型要对应百度给的。适合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,跳到对应的搜索结果。

这里写图片描述

点击后跳转

这里写图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值