为什么脚本不按预期迭代for循环?

时间:2015-09-18 06:36:54

标签: javascript html

我希望在单击提交按钮时,脚本会检查bookDirectory对象中的输入,如果找到,则显示其指定的凭据。但是,它不会这样做,输入栏只是刷新。我做错了什么?

<!DOCTYPE html>
<html>
<head>
  <title>This is just a test</title>
  <script src="script.js"></script>

</head>

<body>
  <h1>This is going to be the search bar</h1>
  <form>
  <input type="text" id="BookName" name="Book1">
  <input type="submit" id="Searchbtn" onclick="algo()">
</form>
  <script>

  var search = document.getElementById('BookName');

  var bookDirectory = {};
  bookDirectory.book1 = {
    bookName : "book1",
    bookTag1 : "MAIT",
    bookTag2 : "3rd Semester"
  };

  bookDirectory.book2 = {
    bookName : "book2",
    bookTag1 : "NIEC",
    bookTag2 : "1st Semester"
  };

  bookDirectory.book3 = {
    bookName : "book3",
    bookTag1 : "USIT",
    bookTag2 : "5th Semester"
  };

  function algo(search){
      for(var name in bookDirectory){
          if(bookDirectory[name].bookName === search){
              alert(bookDirectory[name].bookTag1);
          }
      }
  };
  </script>
  <h2 id="Book1">This is going to be the book</h2>

</body>
</html>

3 个答案:

答案 0 :(得分:0)

您没有将参数传递给算法功能。 从算法功能中删除参数。将您的算法功能更改为

function algo(){
      var search = document.getElementById('BookName').value;
      for(var name in bookDirectory){
          if(bookDirectory[name].bookName === search){
              alert(bookDirectory[name].bookTag1);
          }
      }
  };

答案 1 :(得分:0)

  1. type="submit"更改为键入=&#34;按钮&#34; 提交就像发出服务器请求并刷新页面或使用<button>
  2.   

    <button id="Searchbtn" onclick="algo()"> Test </button>
    
    1. 您没有将搜索参数传递给algo函数
    2. function algo(){

          var search = document.getElementById("BookName").value;
      
          for (var name in bookDirectory) {
              if (bookDirectory[name].bookName === search) {
                  alert(bookDirectory[name].bookTag1);
              }
          }
      };
      

      每次调用函数时从文本框中获取值

答案 2 :(得分:0)

只需更改

onclick="algo()"

onsubmit="algo()"