[英]else condition is always executed even if the if statement is true
我一直在尝试修复此代码:我有一个列表,并且正在搜索列表以查找学生。 一旦我找不到学生,就会出现错误信息。 目前,我有一个功能,可以根据文本匹配来搜索学生。 我在函数内部有一个if语句。 找到匹配项后,显示学生,否则显示隐藏所有学生。 找到学生后,我创建了一个变量“ found”设置为“ true”。 如果为假,则应附加该消息。
问题是似乎都在执行这两个条件,因此,如果我发现第二个条件中的内容为假,则每次都会显示错误消息。
此刻我还有另一个,如果检查是否为假。 问题是它不认识到它是错误的。 请查看控制台的屏幕截图,您会看到尽管找到了学生,但每次都会执行第二个条件... 控制台的屏幕截图-始终执行第二个条件
除非它是真的,否则第一个条件不会执行。
请帮忙,因为我一直试图对此进行调查,并且我在此处就此问题提出了很多问题,但没有什么大的结果。
非常感谢Alina
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();
}
});
我认为该函数被多次调用,以判断“条件2”被记录了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('--------------------------------------');
}
这样一来,您可以看到该函数被调用了多少次
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.