1、效果
如下圖所示,我們?cè)谳斎氪髮W(xué)時(shí),程序會(huì)到后端查詢名字中包含大學(xué)的數(shù)據(jù),并展示到前端頁(yè)面。
用戶選擇一個(gè)大學(xué),該大學(xué)值會(huì)被賦值到input表單,同時(shí)關(guān)閉下拉表單;
當(dāng)頁(yè)面展示的數(shù)據(jù)都不符合條件時(shí),用戶點(diǎn)擊空白處,可關(guān)閉表單。文章來(lái)源:http://www.zghlxwxcb.cn/news/detail-702154.html
2、前端
2.1、頁(yè)面html代碼
文章來(lái)源地址http://www.zghlxwxcb.cn/news/detail-702154.html
<label class="layui-form-label required" th:text="#{register.unit}">單位名稱:</label>
<div class="layui-input-block">
<input type="text" id="UNIT" name="" th:placeholder="#{register.enterUnit}" autocomplete="off" class="layui-input">
</div>
<div id="show" class="layui-form-item" style="display: none"></div>
2.2、頁(yè)面js代碼
<script>
$(function () {
//用于監(jiān)聽(tīng)鍵盤(pán)事件
$("#UNIT").bind('input porpertychange', function () {
var word = $(this).val();
if (word != "") {
$.ajax({
url: "./keyword",
data: {"name": word},
type: "post",
dataType: "json",
success: function (obj) {
console.log(obj);
var htmlStr = "";
for (var i = 0; i < obj.length; i++) {
htmlStr += "<li style='list-style: none' onclick='demo(this)'>" + obj[i] + "</li>";
}
$("#show").html(htmlStr).show();
}
})
} else {
$("#show").hide();
}
})
})
//監(jiān)聽(tīng)用戶點(diǎn)擊li的事件,用戶選擇一個(gè)小li,小li的值被賦值給input,同時(shí)關(guān)閉小li
function demo(dom) {
$("#UNIT").val(dom.innerText);
$("#show").hide();
}
//監(jiān)聽(tīng)鼠標(biāo)點(diǎn)擊事件,當(dāng)后端返回沒(méi)有符合條件的數(shù)據(jù)時(shí),用戶點(diǎn)擊空白頁(yè)面時(shí),關(guān)閉show
$(document).click(function(){
$("#show").hide();
});
</script>
2.3、頁(yè)面css樣式代碼
<style type="text/css">
* {
margin: 0px;
padding: 0px;
}
#UNIT {
width: 100%;
height: 42px;
border-color: #4E6EF2;
float: left;
}
#show {
border: 1px solid #4e6ef2;
position: relative;
left: 20%;
margin-right: 45%;
text-align: left;
}
li:hover{
background-color: rgba(0,120,212, 0.1);
}
</style>
3、后端
@RequestMapping("/keyword")
@ResponseBody
protected List unitData(HttpServletRequest req, HttpServletResponse resp) throws IOException {
List<String> list=new ArrayList<>();
List<String> universities = Arrays.asList("公安局,教育局,北京大學(xué),清華大學(xué),上海交通大學(xué),浙江大學(xué),廈門(mén)大學(xué),河南大學(xué),河北大學(xué), 浙江大學(xué),福建大學(xué),廣東大學(xué),廣西大學(xué),四川大學(xué),山東大學(xué),陜西大學(xué),山西大學(xué),a1,a2,a3,aa,".split(","));
for (String s : universities) {
if(s.contains(req.getParameter("name"))){
list.add(s);
}
}
return list;
}
到了這里,關(guān)于Ajax&JavaScript&css模仿百度一下模糊查詢功能的文章就介紹完了。如果您還想了解更多內(nèi)容,請(qǐng)?jiān)谟疑辖撬阉鱐OY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!