JS/jQuery读取单选按钮评分值写入opinions数组实现咨询
问题原因
- 错误使用
getElementById获取class属性的容器元素,三个评分容器是class属性而非id,无法通过该方法获取到对应元素 - 单选按钮的选中值不能直接读取父容器的
value属性,需要先筛选出组内处于checked状态的单选按钮再读取值 - 第三组1-10分的量表单选按钮,前9个没有设置
value属性,值存储在父级label的value属性中,需要单独处理取值逻辑 - 构造
newOpinion对象时没有加入三个评分字段,所以即使拿到值也不会存入opinions数组和localStorage - 提交事件没有阻止默认行为,表单提交会触发页面刷新,可能导致存储逻辑未执行完成
修复方案
方案1:原生JavaScript实现
直接修改你的processOpnFrmData函数即可,完整修改后代码如下:
function processOpnFrmData(event) { // 阻止表单默认提交刷新页面 event.preventDefault(); const nopName = document.getElementById("menoapriezvisko").value.trim(); const nopEmail = document.getElementById("email").value.trim(); const nopUrl = document.getElementById("url").value.trim(); const nopComm = document.getElementById("komentar").value.trim(); // 修复:获取三组评分选中值 const star1Checked = document.querySelector('.star-rating input[type="radio"]:checked'); const nopStar1 = star1Checked ? star1Checked.value : null; const star2Checked = document.querySelector('.star-rating2 input[type="radio"]:checked'); const nopStar2 = star2Checked ? star2Checked.value : null; const scaleChecked = document.querySelector('.scale-rating input[type="radio"]:checked'); let nopScale = null; if (scaleChecked) { // 优先取input自身value,不存在则取父label的value nopScale = scaleChecked.value || scaleChecked.parentElement.getAttribute('value'); } const nopWillReturn = document.getElementById("willReturnElm").checked; // 补充评分必填校验 if (nopName == "" || nopEmail == "" || nopUrl == "" || nopComm == "" || !nopStar1 || !nopStar2 || !nopScale) { window.alert("Prosím, zadajte všetky údaje."); return; } const newOpinion = { name: nopName, email: nopEmail, url: nopUrl, comment: nopComm, gdpr: nopWillReturn, // 新增三个评分字段存入对象 designRating: nopStar1, contentRating: nopStar2, totalRating: nopScale, created: new Date() }; console.log("Nový názor návštevníka:\n " + JSON.stringify(newOpinion)); opinions.push(newOpinion); localStorage.myTreesComments = JSON.stringify(opinions); //4. Notify the user window.alert("Tvoj názor bol uložený! Pre viac info nahliadni do konzole."); console.log("Nový názor bol pridaný!"); console.log(opinions); //5. Reset the form myFrmElm.reset(); }
方案2:jQuery实现(项目已引入jQuery可使用)
获取评分的逻辑可以简化为以下代码,其余逻辑和原生方案一致:
const nopStar1 = $('.star-rating input[type="radio"]:checked').val(); const nopStar2 = $('.star-rating2 input[type="radio"]:checked').val(); let nopScale = $('.scale-rating input[type="radio"]:checked').val(); if (!nopScale && $('.scale-rating input[type="radio"]:checked').length) { nopScale = $('.scale-rating input[type="radio"]:checked').parent().attr('value'); }
额外注意点
- 建议给第三组评分前9个单选按钮统一加上
value属性,和第10个保持格式一致,可省去读取父label值的兼容逻辑 - 你提供的HTML代码中缺少id为
url、komentar的输入框和id为willReturnElm的复选框,如果原项目中未添加需要补充,否则会出现取值错误
内容的提问来源于stack exchange,提问作者OnlyForFun
相关产品推荐
相关产品推荐

