0
我試圖追加一個錯誤消息到HTML一旦沒有匹配在搜索欄中。我有一個列表,一旦沒有匹配,列表項顯示:none;那是我想要的消息。問題是,在一個循環內循環遍歷列表,這個消息的附加次數與列表項的數量相同。錯誤消息追加只有一次
更新後的代碼:它似乎錯誤消息不會出現每次我搜索不匹配的學生...除非我刷新頁面。有時甚至當我有匹配的學生錯誤顯示,但它不應該。
//add search bar
$(".page-header").append('<div class="student-search"></div>');
$(".student-search").append('<input id="input-search" placeholder="Search for students..."/><button id="search">Search</button>');
$('.page').append('<div class="error"></div>');
$('.error').append('<p>"Student not found!"</p>');
$('.error').hide();
var found = true;
//myFunction
function myFunction() {
var input = document.getElementById("input-search");
var filter = input.value.toUpperCase();
var ul = document.getElementsByClassName("student-list");
var li = document.getElementsByTagName("li");
for (var i = 0; i < li.length; i++) {
var h = li[i].getElementsByTagName("h3")[0];
if (h.innerHTML.toUpperCase().indexOf(filter) > -1) {
li[i].style.display = "";
found = true;
} else {
li[i].style.display = "none";
console.log('Hello! Student is not found!');
found = false;
}
}
$('.pagination').hide();
if (found === false) {
$('.error').show();
}
}
//myFunction end
// when the input is empty return to page 1, empty the error div, show pagination,
$('#input-search').on('keyup', function() {
if($(this).val() === '') {
$('.error').empty();
go_to_page(0);
$('.pagination').show();
}
});
$('#search').click(function(){
myFunction();
});
感謝, 阿麗娜
工作得很好!我只是將變量'found'添加到我的代碼和'if'語句中。我現在唯一的問題是,一旦我刪除當前搜索並鍵入另一個搜索,錯誤文本將被追加並添加到頁面兩次。有沒有辦法讓輸入變空後錯誤消息消失?非常感謝你的幫助! –
完美我更新了我的安納爾 –
嗨喬納森,你又是一個明星!感謝您的幫助。它運行良好,但它有一些錯誤。似乎只有當我第一次搜索未找到的學生,如果我第一次有匹配的學生作爲結果,並且在我再次搜索一個不存在的信息不顯示的情況下,該信息纔會出現。相反,即使我搜索它顯示的現有學生,但它不應該。所以它只認識到'發現'只是一次錯誤,除非我刷新頁面。我在我的問題中更新了我的代碼,我必須在那裏做錯了...... :(請幫助 –