我正在尝试编写代码,我有一个输入框,如果我输入" A"我会得到我阵中所有学生的名字,他们已经获得了#34; A"等级。我觉得我越来越接近,但我不能完全弄清楚我需要做些什么才能使这个代码发挥作用。任何帮助将不胜感激。
<!DOCTYPE html>
<html>
<head>
<title> Javascript </title>
<script>
var students = [
{name:"Lina",grade:"F"},
{name:"Fredrik",grade:"D"},
{name:"Sara",grade:"C"},
{name:"Lucia",grade:"B"},
{name:"Hans",grade:"A"},
{name:"Jonathan", grade: "A"}
]
gradesByLetter = ['A', 'B', 'C', 'D', 'F'].map(function(letter){
return students.filter(function(student){
return student.grade == letter;
});
});
gradesByLetter.forEach(function(list){
list.forEach(function(student){
document.getElementById(student.grade).innerHTML += "<li>" + student.name + " (" + student.grade + ")"
});
});
f1.addEventListener('submit', function(evt){
evt.preventDefault(); //ignore this for now but this will stop the error
studentList.innerHTML += "<li>" + studentName.value + " (" + grade.value + ")"
});
</script>
</head>
<body>
<h1>Min Rubik</h1>
<form id="f1">
<input type="text" id="studentName" placeholder="Student Name">
<input type="text" id="grade" placeholder="Grade">
<input type="submit" value="Add">
</form>
<h2>Students:</h2>
<ul id="studentList">
<ol id="A"></ol>
<ol id="B"></ol>
<ol id="C"></ol>
<ol id="D"></ol>
<ol id="F"></ol>
</ul>
</body>
</html>
答案 0 :(得分:-1)
以下是答案,如果你将成绩留空,它将显示所有学生。
<!DOCTYPE html>
<html>
<head>
<title>Javascript</title>
</head>
<body>
<h1>Min Rubik</h1>
<form id="f1">
<input type="text" id="studentName" placeholder="Student Name">
<input type="text" id="grade" placeholder="Grade">
<input type="button" id="click_me" value="Add">
</form>
<h2>Students:</h2>
<ul id="studentList">
</ul>
<script>
var students = [
{name:"Lina",grade:"F"},
{name:"Fredrik",grade:"D"},
{name:"Sara",grade:"C"},
{name:"Lucia",grade:"B"},
{name:"Hans",grade:"A"},
{name:"Jonathan", grade: "A"}
];
function clickHandler() {
document.getElementById("studentList").innerHTML = "";
students.forEach(function(student) {
if ((student.grade == document.getElementById("grade").value || document.getElementById("grade").value == "") &&
(student.name.toLowerCase() == document.getElementById("studentName").value.toLowerCase() || document.getElementById("studentName").value == "")) {
document.getElementById("studentList").innerHTML += "<li>" + student.name + " (" + student.grade + ")"
}
});
}
document.getElementById("click_me").addEventListener('click',clickHandler);
</script>
</body>
</html>