要实现的 UI 功能
依赖文件:
- jQuery https://jquery.com/
- art-template 模板引擎 https://aui.github.io/art-template/
实现步骤:
- 获取用户输入的 搜索关键字
- 封装函数,用于发送 Ajax 请求
- 利用 模板引擎 渲染 UI 结构
获取用户输入的 搜索关键字
$('#ipt').on('keyup', function() {
var key = $(this).val().trim()
if (key.length <= 0) {
return
}
})
封装 getList 函数
function getList(key) {
$.ajax({
url: 'https://suggest.taobao.com/sug?q=' + kw,
dataType: 'jsonp',
success: function(res) {
console.log(res) }
})
}
利用 模板引擎 渲染 UI 结构
<script type="text/html" id="tpl-suggestList">
{
{
each result}}
<div class="suggest-item">{
{
$value[0]}}</div>
{
{
/each}}
</script>
<script>
function readerList(res) {
if (res.result.length <= 0) {
return $("#suggest-list").empty().hide()
}
let htmlStr = template("tpl", res)
$("#suggest-list").html(htmlStr).show()
}