【发布时间】:2017-04-29 21:35:46
【问题描述】:
我一直在尝试修复此代码:我有一个列表,我正在搜索列表以查找学生。一旦我找不到学生,就会出现一条错误消息。目前我有一个基于文本匹配搜索学生的功能。我在函数中有一个 if 语句。找到匹配时显示学生,否则隐藏所有学生。当找到学生时,我创建了一个变量 'found' 设置为 'true'。如果这是错误的,则应附加消息。
问题是这两个条件似乎都在执行,所以如果我在第二个条件中将 found 设置为 false,则每次都会显示错误消息。
目前我有另一个 if 检查是否找到是假的。问题是它不承认它是错误的......所以令人困惑。请看控制台截图,你可以看到虽然找到了学生,但每次都执行第二个条件...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();
}
});
【问题讨论】:
标签: javascript debugging if-statement