引入资源
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>