简体   繁体   English

功能未按正确顺序运行

[英]functions not running in the right order

in my while loop I was hoping it will keep prompting the user for entry unless I break out of the loop.在我的while循环中,我希望它break不断提示用户输入,除非我跳出循环。 However, once I get into my if block it wont to peform printToScreen(message) function unless I terminate the code.但是,一旦我进入我的if块,除非我终止代码,否则它不会执行printToScreen(message) function。

Not sure what I am doing wrong here.不知道我在这里做错了什么。 I am expecting it to print message before continuing to prompt.我希望它在继续提示之前打印消息。 how can I fix this?我怎样才能解决这个问题?

let message;
let search;

function printToScreen(message){
  let outputDiv = document.getElementById('output');
  outputDiv.innerHTML = message;  
}

function promptUser (){
    search = prompt("Enter student name");
return search;
}


function searchStudent(){

  while(true){

  search =promptUser();

  for(let i = 0; i<students.length; i++){

    if(search.toLowerCase() === students[i].name.toLowerCase())
    {
      let student = students[i];
      message = `<h4>Student: ${student.name}</h4>`; 
      message += `<p> Track: ${student.track} 
                  <br> Achievements:${student.achievements}
                  <br> Points: ${student.points}
                  </p>`; 
      printToScreen(message);
    }

    else if( search ===null || search.toLowerCase() === 'quit'){
      message = `<p>Thanks.Goodbye! </p>`;

      printToScreen(message);
      break;
    }   
    else{
         message = `<p> Student ${search} does not exist. Try Again!</p>`;
         printToScreen(message);
        }      
     }
  }
}
searchStudent();

That's because the browser won't redraw the page while it is still computing some js.那是因为浏览器在计算一些 js 时不会重绘页面。 What you could do is replace your while(true) by a recursive call in a setTimeout:您可以做的是用 setTimeout 中的递归调用替换您的 while(true):

function searchStudent(){

  search =promptUser();

  for(let i = 0; i<students.length; i++){

    if(search.toLowerCase() === students[i].name.toLowerCase())
    {
      let student = students[i];
      message = `<h4>Student: ${student.name}</h4>`; 
      message += `<p> Track: ${student.track} 
                  <br> Achievements:${student.achievements}
                  <br> Points: ${student.points}
                  </p>`; 
      printToScreen(message);
    }

    else if( search ===null || search.toLowerCase() === 'quit'){
      message = `<p>Thanks.Goodbye! </p>`;

      printToScreen(message);
      break;
    }   
    else{
         message = `<p> Student ${search} does not exist. Try Again!</p>`;
         printToScreen(message);
    }      
  }

  setTimeout(function(){
      searchStudent();
  },5);
}
searchStudent();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM