我有一个显示列表项的搜索框,并在用户单击按钮后清除搜索字段...但如果用户要再次搜索,我该如何删除搜索到的项目?因此页面仅显示新的搜索结果,而不是之前的
var noNameFound = true;
var searchedStudent = [];
// Stores names in an array where names can be pulled and shown when button is clicked
var studentArr = [];
$('.student-list').children().each(function(){
studentArr.push(this);
});
// this will search through the array to locate the student.
$('.userSearch').on('click', function(){
//stores users search into a variable
var searchRequest = $('#search-input').val();
//search through array here...
for (var i = 0; i < studentArr.length; i++) {
var studentstr = studentArr[i].innerText;
if (studentstr.indexOf(searchRequest) !== -1) {
console.log('YAY!! the name:: ' + searchRequest + ' ::is in our list');
$(".student-list li").css("display","none"); // removes all students from the list.
searchedStudent.push(studentArr[i]);
$(searchedStudent).show(); // displayes the searched student.
noNameFound = false;
}
}
// removes stundent-item if no user can be found, and asks user to click buttont to refresh page.
if (noNameFound) {
var errorMessage = $('<p class="errMessage">Sorry but we were unable to locate the name you were looking for, <br> please click <button class="refresh">here</button> to refresh the page and try again.</p>');
$(".student-list").prepend(errorMessage);
$('.student-item').css('display', 'none');
$('.refresh').on('click', function(){
location.reload();
});
}
if(noNameFound){
//stops users searching an empty search field.
$('.userSearch').prop('disabled',true);
$('#search-input').keyup(function(){
$('.userSearch').prop('disabled', this.value === ""? true : false);
});
}
});
这是我到目前为止所拥有的
答案 0 :(得分:0)
您需要在点击事件处理程序中的searchedStudent
循环之前重置for
数组。
// rest of the code
// this will search through the array to locate the student.
$('.userSearch').on('click', function(){
//stores users search into a variable
var searchRequest = $('#search-input').val();
searchedStudent = []; // <<<<<<<<<<<<<<< HERE
//search through array here...
for (var i = 0; i < studentArr.length; i++) {
var studentstr = studentArr[i].innerText;
// rest of the code
实际上你可以完全删除searchedStudent
数组并仍然实现功能..试一试。