
本文介绍如何使用原生 javascript 获取 html 中已选中的星级评分(radio 按钮组)的数值,并通过弹窗反馈结果,适用于无框架的轻量级交互场景。
本文介绍如何使用原生 javascript 获取 html 中已选中的星级评分(radio 按钮组)的数值,并通过弹窗反馈结果,适用于无框架的轻量级交互场景。
在构建用户评价组件时,常需将用户点击的星级(如 1–5 星)转换为可处理的数值。上述 HTML 使用一组 name="rating" 的 <input type="radio"> 实现单选星级,关键在于:只有被选中的 radio 元素才具有 :checked 状态。因此,我们可通过 CSS 伪类选择器精准定位该元素,并读取其 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() {
const selectedRadio = document.querySelector('input[name="rating"]:checked');
if (!selectedRadio) {
alert('Please select a rating first!');
return;
}
const rating = selectedRadio.value;
console.log('Selected rating:', rating); // 如:'3'
alert(`Thank you! You have submitted ${rating} stars.`);
}
</script>✅ 核心要点说明:
- document.querySelector('input[name="rating"]:checked') 是最简洁、标准的获取方式,利用浏览器原生支持的属性选择器与伪类组合;
- 必须加空格或明确限定作用域(如 .star-rating input:checked),避免误选其他同名表单控件;
- 务必检查返回值是否为 null —— 若用户未做任何选择,querySelector 返回 null,直接调用 .value 会抛出 TypeError;示例中已添加防御性判断;
- 不推荐使用 getElementsByName() + 循环遍历,既冗余又易出错;
- 若后续需支持动态渲染或多次提交,建议将事件监听改为 addEventListener 方式,解耦 HTML 与 JS(例如:document.getElementById('btn').addEventListener('click', myFunction))。
掌握这一模式后,你不仅能轻松读取星级,还可扩展至任意单选评分、满意度选项等场景,是前端表单交互的基础必备技能。

















