0
我已經寫了一個示例自動填充應用程序,可以按我的意圖工作。如何重構我的自動填充應用程序
HTML
<div class="wrapper">
<div class="search">
<input type="text" id="search" placeholder="Search" onkeyup="autoComplete(this.value)">
<button onclick="search()">Go</button>
<ul id="suggest">
</ul>
</div>
<div class="result">
</div>
</div>
腳本
var data = ['Bob', 'Aria', 'Smith', 'Jack', 'Cethy', 'Brad', 'Jony', 'Dan', 'Ashley', 'Janice'];
var suggestionArray = [];
var search = function(){
var searchTerm = document.getElementById('search').value;
if(searchTerm == undefined || searchTerm == ""){
return false;
}
console.log('You are searching for ' + searchTerm);
}
var clearSuggestion = function() {
suggestionArray = [];
}
var addListenersToChild = function(){
var el = document.getElementById('suggest');
el.addEventListener('click', function(event){
var searchTerm = event.target.textContent;
document.getElementById('search').value = searchTerm;
clearSuggestion();
showSuggestion();
}, false)
}
var showSuggestion = function(){
var el = document.getElementById('suggest');
el.innerHTML = "";
if(suggestionArray.length>0){
suggestionArray.forEach(function(suggestTerm){
var node = document.createElement('li');
var textnode = document.createTextNode(suggestTerm);
node.appendChild(textnode);
el.appendChild(node);
});
addListenersToChild();
}
}
var formSuggestionArray = function(dataTerm){
if(suggestionArray.indexOf(dataTerm) > -1){
return false;
} else {
suggestionArray.push(dataTerm);
}
}
var matchVal = function(val){
clearSuggestion();
for(var i=0; i<data.length;i++){
if(data[i].toLowerCase().indexOf(val.toLowerCase()) > -1) {
formSuggestionArray(data[i]);
}
}
}
var autoComplete = function(val){
if(val == undefined || val == ""){
clearSuggestion();
showSuggestion();
return false;
}
matchVal(val);
showSuggestion();
}
我不知道,如果我寫的代碼的方式是這樣做的最佳方式。因此,舉例來說,我需要知道的是,如果我現在的計劃是
- 良好的可讀性
- 優化
- 遵循最佳做法或不
我怎樣才能提高代碼
非常感謝您的投入..真正感激 –