簡體   English   中英

else條件始終執行,即使if語句為true

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM