淘宝搜索框案例

引入资源  

jquery

<script src="http://www.wsg3096.com/ass/jquery-3.6.0.js"></script> 

模板引擎

  <script src="http://www.wsg3096.com/ass/template-web.js"></script> 

初始化样式

  <link rel="stylesheet" href="http://www.wsg3096.com/ass/initialize.css">

CSS:

.tags span{
      display: inline-block;
      padding: 6px 12px;
    }
    .on8{
      color: white;
      background: #f35;
    }
    #inp{
      width: 620px;
      height: 48px;
      padding-left: 12px;
      outline: none;
      border-color: #f35;
    }
    #btn{
      width: 80px;
      height: 48px;
      color: white;
      background: #f35;
      border: none;
    }

    #suggest-list{
      width: 620px;
      border: 1px solid #cccccc;
    }

    .suggest-item{
      width: 100%;
      line-height: 36px;
      padding-left: 12px;
    }
    .suggest-item:hover{
      background: #e5e5e5;
    }

 HTML:

<img src="pic/520.png" alt="" style="margin: 100px auto 40px;width: 400px">
<div class="juzhong" style="width: 700px">
  <div class="tags">
    <span class="on8">宝贝</span>
    <span>店铺</span>
  </div>
  <input type="text" placeholder="输入要搜索的内容" id="inp"><button id="btn">搜索</button>
  <div id="suggest-list"></div>
</div>

JS

<script type="text/html" id="tpl-sug">
  {{each result}}
  <div class="suggest-item">{{$value[0]}}</div>
  {{/each}}
</script>

<script>
  $(function () {

    // 定义全局缓存对象
    let cacheObj = {}

    // 定义防抖函数
    let timer = null
    function debounceSearch(kw) {
      timer = setTimeout(() => {
        getSuggestList(kw)
      },500)
    }

    // 键盘弹起事件
    $('#inp').on('keyup',function () {
      clearTimeout(timer)
      let secStr = $(this).val().trim()
      if (secStr.length <= 0){
        return $('#suggest-list').empty().hide()
      }else {
        if (cacheObj[secStr]){
          return renderSuggestList(cacheObj[secStr])
        }
        // 用防抖获取搜索建议列表
        debounceSearch(secStr)
      }
    })

    // 发起请求函数
    function getSuggestList(kw) {
      $.ajax({
        // 指定请求的URL地址 其中 q 是用户输入的关键字
        url:'https://suggest.taobao.com/sug?q='+kw,
        // 指定要发起的是JSONP请求
        dataType:'jsonp',
        success:res => {
          console.log(res)
          renderSuggestList(res)
        }
      })
    }

    // 渲染搜索提示函数
    function renderSuggestList(res) {
      if (res.result.length <= 0){
        return $('#suggest-list').empty().hide()
      }else {
        let htmlStr = template('tpl-sug',res)
        $('#suggest-list').html(htmlStr).show()

        // 将搜索的结果 添加到缓存对象中
        let k = $('#inp').val().trim()
        cacheObj[k] = res
      }
    }


  })
</script>

  • 1
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值