實現思路:
1,html樣式結構寫好
2,點擊搜索按鈕時在這個事件方法中,獲取input中的值,調用發送ajax請求的方法,請求成功后用拼接模板字符串來渲染搜索到的商品頁面,
3,(歷史記錄功能)每次點擊搜索將這個值存放到一個數組中,將這個數組遍歷,遍歷中寫拼接模板字符串進行渲染到頁面,
- 將這個空數組在點擊事件的外邊聲明
- 對這個數組進行去重和截取保留后5個歷史記錄的值(我項目中要求只保留5個值)
4,再給每個歷史記錄的li標簽注冊點擊事件,在點擊每個歷史記錄li時調用發送ajax請求方法,請求商品頁面,
<div id="serach" style="width: 96%;height: 100vh;position: relative;"> <div> <!-- [#--input搜索--] --> <div class="serachHead"> <div class="searchicon"></div> <input class="serachInput" type="text" value="" placeholder="請輸入商品名"/> <div class="searchButton">搜索</div> </div> <!-- [#--歷史搜索記錄--] --> <div class="history" style="margin: 10px;"> <span>歷史搜索</span> <div class="historyList"> <ul id="historyList" class="clearfix"> </ul> </div> </div> <!-- [#--商品展示--] --> <div class="clearfix" style="padding-bottom: 100px;"> <!--單個商品渲染--> <div class="singleproList"> </div> <!--多個商品渲染--> <div id="MultipleproListMore"> </div> </div> </div> </div>
<script type="text/javascript"> var newSum = []; $(".searchButton").click(function(){ var $serachInput = $(".serachInput").val(); if($serachInput !== ""){ // 獲取到值后發送請求 getAjax($serachInput); // 對數據進行處理 newSum.unshift($serachInput) let setSum = [...new Set(newSum)]; let spliceSum = setSum.splice(0,5); console.log(spliceSum,"新的數組"); // 遍歷數組中的值,渲染頁面 let htmlStr = ""; spliceSum.forEach(function(item,index){ htmlStr += "<li class='listLi'>"+ item +"</li>"; }); $("#historyList").html(htmlStr); // 給每個li注冊點擊事件,傳值調用ajax請求 $(".listLi").click(function(){ console.log("li點擊事件") // this.innerText 獲取到li中的文本(搜索的商品名) getAjax(this.innerText); }); } }); function getAjax(value){ console.log(value,"發送ajax請求"); // $.ajax({ // url:"", // type:"get", // data:{keyWord:value}, // dataType:"json", // cache:false, // success:function(res){ // // 請求過來的數據用字符串拼接,然后渲染到頁面中 // } // }); } </script>