JSsearch實如今購物網站輸入後推薦聯想的效果

在篇文章裏,咱們主要講解一下JSsearch如何完成推薦的功能javascript

首先,登錄碼雲下載JSsearch:css

https://gitee.com/skyogo/JSsearchhtml

咱們下載JSsearch1.0 Community版本java

下載好了以後咱們再下載一個相似淘寶的購物頁面(頁面由達內童程製做,感謝他們)git

連接:https://pan.baidu.com/s/1eSYCWee  密碼:ptq2數組

而後,咱們打開這個頁面,會發現是這樣的工具

此時咱們關掉頁面,將咱們的JSsearch.js拷貝一份到淘寶頁面的根目錄的js文件夾下面開發工具

拷貝完了以後,咱們在html頁面中引入它(在body最底部寫).net

<script src="js/JSsearch.js"></script>
<script>
   
</script>

而後咱們在上面的第76行(input標記下面)裏寫上這段代碼code

<div id="search-recommend">
 沒有搜索結果
</div>

而後咱們打開css/index.css文件,在裏面寫上這段css樣式表

#search-recommend{
    height: 40px;
    width: 580px;
    position: absolute;
    top: 110px;
    border: 1px gray solid;
    padding-left: 20px;
    box-sizing: border-box;
    padding-top: 11px;
    font-size: 15px;
    cursor: pointer;
    background: white;
}

運行一下html頁面,發現搜索框下面多出了一個框

至此,咱們的html和css代碼就寫完了,接下來,咱們來寫js代碼

咱們如今將頁面關閉,打開開發工具,在index.html裏面找到大約是2754行的<script>標籤,那麼咱們如今就要在裏面寫入咱們的查詢代碼

首先,咱們寫入這段代碼:(重複獲取輸入框裏面的值)

var lastValue = document.getElementById("search-in").value;
setInterval(function(){
    
                
},10)

而後,咱們在var的下面寫入判斷語句,判斷是否輸入框的值改變了

if(lastValue != document.getElementById("search-in").value){
                    
}

接着,咱們在if裏面寫入:

lastValue = document.getElementById("search-in").value;

這段話,就是說重複判斷,若是輸入框的值改變了,那麼就從新賦值

而後,咱們再在下面寫入:

if(lastValue==null||lastValue==""){
    document.getElementById("search-recommend").innerHTML = "沒有搜索結果";
}else{

}

這段話,就是判斷若是輸入框如今的值爲空,那麼就讓他顯示「沒有搜索結果」

接着,咱們在else裏面寫入:

var newItemList = JSsearchByKeyWord(itemList,lastValue);
if(newItemList[0] == undefined){
     document.getElementById("search-recommend").innerHTML = "沒有搜索結果";
}else{
  
}

這時,咱們就調用了JSsearch的用關鍵詞查找的方法,哦,對了,咱們還沒寫itemList這個數組

這時把光標移到setInterval的上面一行,寫上:

var itemList = ["光能表","情侶表","日韓腕錶","手錶放心淘","瑞士表","陶瓷表","電子錶","歐米茄","鋼帶表","皮帶表","鏤空機械錶","斯沃琪","天梭","運動表","卡西歐","國表","時尚表","女表","兒童表","學生表","浪琴"];

itemList是咱們全部的商品合集

如今再把光標移回去,移到else裏面,寫上:

document.getElementById("search-recommend").innerHTML = newItemList[0];

此時,咱們再打開html文件,再輸入框裏面輸入內容,就會發現已經有聯想了!

固然,這還只是個雛形,咱們還有一個BUG須要解決,就是當你輸入一個多個字符串都含有的字符後,他並不必定推薦你想的那個,這點JSsearch已經幫咱們想好了,我在這裏就再也不寫了,若是想解決這個BUG,能夠參考JSsearch的說明文檔自行解決!

最後,再從新說一遍JSsearch的連接:(開源中國)

https://www.oschina.net/p/jssearch

相關文章
相關標籤/搜索