我正在努力修复此代码:我有一个列表,我正在搜索列表中找到学生。一旦我找不到学生,就会出现错误信息。目前我有一个基于文本匹配搜索学生的功能。我在函数内部有一个if语句。当找到比赛显示学生时,如果没有,则隐藏所有学生。我创建了一个变量' found'设为' true'什么时候找到学生。如果这是假的,则应附加消息。
问题是两个条件都正在执行似乎如果我在第二个条件中将find发现为false,每次都会显示错误消息。
目前我还有另一个检查是否发现是假的。问题是它没有认识到这是错误的......所以令人困惑。请查看控制台的屏幕截图,您可以看到虽然找到了学生,但每次都会执行第二个条件...... screenshot with the console - second condition is always executed
除非条件成立,否则第一个条件不会执行。
请帮助我,因为我试图永远调查这个问题,我在这个问题上提出了很多问题,但没有大的结果。
非常感谢, 阿丽娜
var ul = document.getElementsByClassName("student-list");
var li = document.getElementsByTagName("li");
//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>');
// append to the .page the container div for the error message
$('.page').append('<div class="error"></div>');
// append to the error div a p with the error message if student is not found
var found = true;
//myFunction
function myFunction() {
var input = document.getElementById("input-search");
var filter = input.value.toUpperCase();
for (var i = 0; i < li.length; i+=1) {
var h = li[i].getElementsByTagName("h3")[0];
if (h.innerHTML.toUpperCase().indexOf(filter) != -1) {
li[i].style.display = "";
console.log('yey found it');
found = true;
} else {
li[i].style.display = "none";
console.log('condtion 2');
}
}
if (found===false) {
$('.error').append('<p>"student not found!"</p>');
}
$('.pagination').hide();
}
//myFunction end
$('#search').on('click', function(){
myFunction();
});
// when the input is empty return to page 1, empty the error div, show pagination,
$('#input-search').on('keyup', function() {
if($(this).val() === '') {
go_to_page(0);
$('.pagination').show();
}
});
答案 0 :(得分:1)
我认为该功能不止一次被判断为判断条件2&#39;记录了50次,每次条件都不满意, 为了确保即使代码输入if语句它也没有到达else语句,编辑函数是这样的:
function myFunction() {
var input = document.getElementById("input-search");
var filter = input.value.toUpperCase();
found = false
for (var i = 0; i < li.length; i+=1) {
var h = li[i].getElementsByTagName("h3")[0];
if (h.innerHTML.toUpperCase().indexOf(filter) != -1) {
li[i].style.display = "";
console.log('yey found it');
found = true;
} else {
li[i].style.display = "none";
console.log('condtion 2');
}
}
if (found===false) {
$('.error').append('<p>"student not found!"</p>');
}
$('.pagination').hide();
console.log('--------------------------------------');
}
通过这种方式,您可以看到调用函数的次数