DOM调用对象

时间:2015-12-17 05:45:50

标签: javascript object dom

我已尝试使用调试器,但仍然不明白为什么无论我输入什么内容,此函数都会不断打印数组中的第一个对象。

我想要做的是迭代每个数组元素,如果文本框中的输入等于其中一个名称属性,则打印该名称的信息。

我认为一个简单的for循环检查文本框中的输入是否等于任何名称属性,然后是console.log,该数组元素将起作用。

HTML:

<script type = "text/javascript" src="js/ObjectTest.js"></script>
<input type = "text" name = "name" id = "name"> </input>
<button type = "submit" id = "submit" onclick = "findStudent()">Find Student </button>

使用Javascript:

var registeredStudents = [
  {name: "Matthew", GPA: 5.0, Faculty: "Science", Major: "Cognitive Systems"},
  {name: "Rohit", GPA: 5.0, Faculty: "Science", Major: "Micro-Biology"},
  {name: "Marcel", GPA: 5.0, Faculty: "Engineering", Major: "Undeclared"},
  {name: "Louis", GPA: 5.0, Faculty: "Engineering", Major: "Mechanical Engineering"},
  {name: "Rob", GPA: 5.0, Faculty: "Engineering", Major: "Mechanical Engineering"}
];

function findStudent(){
  var submit = document.getElementById('name');
    for (var i = 0; i < registeredStudents.length; i++){
      if (submit.value = registeredStudents[i].name){
        console.log(registeredStudents[i]);
        break;
      } else if (submit.value != registeredStudents[i]){
        console.log("Not a registered student");
      }
    }
}

1 个答案:

答案 0 :(得分:1)

如果条件错误,则应==而不是=

function findStudent(){   var submit = document.getElementById(&#39; name&#39;);     for(var i = 0; i&lt; registeredStudents.length; i ++){       if(submit.value == registeredStudents [i] .name){         的console.log(registeredStudents [I]);         打破;       } else if(submit.value!= registeredStudents [i]){         console.log(&#34;不是注册学生&#34;);       }     } }