input的autocomplete效果 ---又是一道騰訊編程題

題目

頁面內有一個 input 輸入框,實現在數組 arr 查詢命中詞並和 autocomplete 效果。

效果

忽略圓圈,這是quickTime錄屏的side effect。。。
這裏寫圖片描述

代碼

html

 <div id="div1">
    <input type="text" id="input" placeholder="有autocomplete的輸入框"/>
    <ul id="ul">
    </ul>
  </div>

css

*{
    margin: 0;
    padding: 0;
    box-sizing:border-box;

}
#div1{
    margin:200px auto;
    position: relative;
}

ul{
    list-style: none;
    margin: 0 auto;
    background-color: #ededed;
    color: #3b200c;
    width: 400px;
    border: none;
}

li{
    cursor: pointer;
}

input{
    display: block;
    margin: 0 auto;
    line-height: 40px;
    height: 40px;
    width: 400px;
    font-size: 20px;
    background-color: #ede387;
    border: none;
}

js

var arr = ['a','apple','abandon','bilibili','beep','before','become','being','highmaintains','by','bye','banana']

input.addEventListener('input', function(event){

    var _value = event.target.value.trim()

    if(_value){

        autoComplete(_value, arr)
    }

    else{

        ul.innerHTML = ''
    }

})


function autoComplete(str, arr){

    var lis = []

    arr.forEach( (word)=>{

        if(word.startsWith(str)){

            lis.push('<li>' + word + '</li>')
        }
    })

    ul.innerHTML = lis.join('')
}

function addToInput(li){

    var _txt = li.innerText

    input.value = _txt
}

ul.addEventListener('click', function(event){

    if(event.target.tagName.toLowerCase() === 'li'){

        addToInput(event.target)
    }
})

思考

之前做過一個前端搜索的,那個還嵌套了兩層,所以這個就駕輕熟路啦。

如果數據量比較大的話,可以用一些搜索的算法,比如二分或者基類等。也可以給數組先排個序。

如果對字符串是模糊搜索的話,可以用kmp算法。

這裏想的比較簡單。就是看首字母。startsWith() 好像是es6 的功能吧。

當然,如果數據量更大的話,通常就交給後端了,前端會調用接口來返回結果。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章