本文介绍如何使用原生 javascript 获取 html 中已选中的星级评分(radio 按钮组)的数值,并通过弹窗反馈结果,适用于表单提交、用户评价等场景。
本文介绍如何使用原生 javascript 获取 html 中已选中的星级评分(radio 按钮组)的数值,并通过弹窗反馈结果,适用于表单提交、用户评价等场景。
在构建用户评分功能时,常使用一组 type="radio" 元素模拟星级选择(如 1–5 星)。关键在于:如何准确、健壮地读取当前被选中的选项值? 正确做法是利用 CSS 伪类 :checked 配合 querySelector,精准定位已选中的 元素并提取其 value 属性。
以下是完整可运行的示例代码:
<div class="star-rating">
<input type="radio" id="5-stars" name="rating" value="5" />
<label for="5-stars" class="star">★</label>
<input type="radio" id="4-stars" name="rating" value="4" />
<label for="4-stars" class="star">★</label>
<input type="radio" id="3-stars" name="rating" value="3" />
<label for="3-stars" class="star">★</label>
<input type="radio" id="2-stars" name="rating" value="2" />
<label for="2-stars" class="star">★</label>
<input type="radio" id="1-star" name="rating" value="1" />
<label for="1-star" class="star">★</label>
</div>
<button id="btn" onclick="myFunction()">Submit</button>
<script>
function myFunction() {
// ✅ 正确:选择 name="rating" 且处于 checked 状态的 input 元素
const selectedRadio = document.querySelector('input[name="rating"]:checked');
// ⚠️ 注意:必须检查是否存在选中项,避免报错
if (!selectedRadio) {
alert("Please select a rating before submitting.");
return;
}
const ratingValue = selectedRadio.value;
console.log("Selected rating:", ratingValue); // 输出如 "3"
alert(`Thank you! You have submitted ${ratingValue} stars.`);
}
</script>关键要点说明:
分析 Java Spring Boot 后端 Controller 代码,自动生成 Markdown 格式的接口文档。当用户说“生成 Java 接口文档”、“生成 API 文档”、“从 Spring 代码生成文档”时触发。
- document.querySelector('input[name="rating"]:checked') 是核心选择器,它会返回第一个匹配的已选中 radio 元素(符合语义与 DOM 规范);
- 务必添加空值判断:若用户未做任何选择,该方法返回 null,直接调用 .value 会抛出 TypeError;
- 推荐将逻辑封装为独立函数并绑定到按钮点击事件(如本例),而非依赖内联 onclick,便于后续维护与测试;
- 如需支持更复杂的交互(如实时预览、禁用提交、表单验证),可进一步结合 addEventListener 和 change 事件监听。
掌握这一模式后,你不仅能处理星级评分,还可轻松扩展至任意单选按钮组(如满意度、难度等级等)的值获取场景。
立即学习“Java免费学习笔记(深入)”;

















