HTML:
<table>
<tr>
<th>Student Name</th>
<th>Student Grades</th>
</tr>
<tr>
<td>
<select name="dropdown" id="dropdown">
<option> - </option>
<option id = "StudentA"> Student A </option>
<option id = "StudentB"> Student B </option>
</select>
</td>
<td></td>
<td></td>
</tr>
<tr>
<td>
<select name="dropdown" id="dropdown">
<option> - </option>
<option id = "StudentA"> Student A </option>
<option id = "StudentB"> Student B </option>
</select>
</td>
<td></td>
<td></td>
</tr>
</table>
JSON:
{"students":
[ {"studentName" : "studentA", "studentGrades" : "gradeC"}, {"studentName" : "studentB", "studentGrades" : "gradeA+"},
]
}
当我选择学生a的下拉选项时,如何使学生成绩自动显示在表上?
我只解析了responsetext,做了一个控制台日志,并完成了它。控制台上有所有的学生,但不完全确定如何使用select选项下拉列表来完成它。
您可以尝试以下方法来实现这一点。在选择标记上添加onchange
事件,并根据所选选项更新成绩列。
完整工作代码:
const data = {
"students": [{
"studentName": "studentA",
"studentGrades": "gradeC"
}, {
"studentName": "studentB",
"studentGrades": "gradeA+"
}, ]
}
function showGrades() {
const dropdowns = document.querySelectorAll('#dropdown')
dropdowns.forEach(dropdown => {
const selectedVal = dropdown.options[dropdown.selectedIndex].id
const formattedVal = selectedVal.charAt(0).toLowerCase() + selectedVal.slice(1)
const grades = data.students.map(item => {
if (item.studentName == formattedVal) {
dropdown.parentElement.parentElement.children[1].innerText = item.studentGrades;
}
})
})
}
<table>
<tr>
<th>Student Name</th>
<th>Student Grades</th>
</tr>
<tr>
<td>
<select name="dropdown" id="dropdown" onchange="showGrades()">
<option> - </option>
<option id="StudentA"> Student A </option>
<option id="StudentB"> Student B </option>
</select>
</td>
<td></td>
</tr>
<tr>
<td>
<select name="dropdown" id="dropdown" onchange="showGrades()">
<option> - </option>
<option id="StudentA"> Student A </option>
<option id="StudentB"> Student B </option>
</select>
</td>
<td></td>
</tr>
</table>
希望这就是你想要的工作方式。
您可以通过在select时触发onchange
事件,然后使用Array.filter()
方法过滤出学生数组来获得所选选项studentGrade
来实现。
工作演示:
const obj = {
"students": [
{"studentName" : "studentA", "studentGrades" : "gradeC"},
{"studentName" : "studentB", "studentGrades" : "gradeA+"},
]
};
function getGrades() {
const selectedOption = document.getElementById('dropdown').value;
document.getElementById('studentGrade').innerHTML = obj.students.find((obj) => obj.studentName === selectedOption).studentGrades;
}
<table>
<tr>
<th>Student Name</th>
<th>Student Grades</th>
</tr>
<tr>
<td>
<select name="dropdown" id="dropdown" onchange="getGrades()">
<option> - </option>
<option value="studentA"> Student A </option>
<option value="studentB"> Student B </option>
</select>
</td>
<td id="studentGrade"></td>
</tr>
</table>