如何使用JavaScript将两个HTML SELECT下拉框值保存为键值对?
实现科目与对应分数的键值对存储
首先要注意:你给出的示例对象结构存在问题——对象中不能有重复的键(subject重复出现会导致后面的条目覆盖前面的),所以推荐两种更合理的存储结构:
推荐的存储结构
1. 数组结构(适合保留添加顺序、允许重复科目场景)
const studentScores = [ { subject: 'Mathematics', score: '75' }, { subject: 'English', score: '88' } ];
2. 对象结构(适合科目唯一,快速通过科目名查找分数)
const studentScores = { Mathematics: '75', English: '88' };
完整实现代码
HTML部分(补充数字下拉框和保存按钮)
<select id="subject" name="subject"> <option value="">Choose Subject</option> <option value="Mathematics">Mathematics</option> <option value="English">English</option> <option value="Geography">Geography</option> <option value="Mathematics Literacy">Mathematics Literacy</option> <option value="Physical Science">Physical Science</option> <option value="Cat">Cat</option> <option value="Life Sciences">Life Sciences</option> <option value="Accounting">Accounting</option> <option value="History">History</option> <option value="Life Orientation">Life Orientation</option> </select> <select class="1-100" name="score"></select> <button id="saveScore">保存科目分数</button>
jQuery逻辑(生成数字下拉框+保存逻辑)
$(function(){ // 生成1-100数字下拉框 const $scoreSelect = $(".1-100"); for (let i = 1; i <= 100; i++) { $scoreSelect.append($('<option></option>').val(i).text(i)); } // 初始化存储容器(这里用数组结构,可根据需求换成对象) let studentScores = []; // 绑定保存按钮点击事件 $('#saveScore').on('click', function() { const selectedSubject = $('#subject').val(); const selectedScore = $scoreSelect.val(); // 校验输入合法性 if (!selectedSubject || !selectedScore) { alert('请先选择科目和分数'); return; } // 检查科目是否已存在,存在则更新分数,不存在则新增 const existingItemIndex = studentScores.findIndex(item => item.subject === selectedSubject); if (existingItemIndex !== -1) { studentScores[existingItemIndex].score = selectedScore; } else { studentScores.push({ subject: selectedSubject, score: selectedScore }); } // 查看存储结果(可替换为后端提交等逻辑) console.log('当前已保存的科目分数:', studentScores); }); });
如果需要对象结构的存储
只需修改初始化和保存逻辑部分:
// 初始化对象结构存储容器 let studentScores = {}; $('#saveScore').on('click', function() { const selectedSubject = $('#subject').val(); const selectedScore = $scoreSelect.val(); if (!selectedSubject || !selectedScore) { alert('请先选择科目和分数'); return; } // 直接赋值,已存在的科目会自动覆盖旧分数 studentScores[selectedSubject] = selectedScore; console.log('当前已保存的科目分数:', studentScores); });
内容的提问来源于stack exchange,提问作者kuhle
相关产品推荐
相关产品推荐

