You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何根据单选框(radio)输入设置标签(label)的文本内容?

这里有个实用的小方案,能实现点击单选框时动态更新指定标签的文本内容,具体实现如下:

核心逻辑

点击不同的单选框时,触发对应的JS函数,把预先指定的元素(id为selectnumber)的内容替换成当前单选框的标识。

完整代码

HTML 部分

<ul>
  <li>
    <fieldset class="rating">
      <legend>Please rate:</legend>
      <input type="radio" id="star5" onclick="handleClick('star5')" name="rating" value="5" />
      <label for="star5" title="Rocks!">5 stars</label>
      <input type="radio" id="star4" onclick="handleClick('star4')" name="rating" value="4" />
      <label for="star4" title="Pretty good">4 stars</label>
      <!-- 可按需补充star3、star2、star1的类似结构 -->
    </fieldset>
  </li>
</ul>
<!-- 用来显示选中标识的目标元素 -->
<div id="selectnumber"></div>

JavaScript 部分

<script>
  handleClick = function(val) {
    document.getElementById('selectnumber').innerHTML = val;
  };
</script>
代码说明
  • 每个单选框都绑定了onclick事件,点击时会把自身的标识(比如star5)作为参数传给handleClick函数
  • handleClick函数通过getElementById找到id为selectnumber的元素,然后用innerHTML把它的内容更新为传入的标识值
  • 你可以根据需求灵活调整:比如把传入的参数换成单选框的value值(比如'5')或者label的文本,只需要修改onclick里的参数即可~

内容的提问来源于stack exchange,提问作者Oz Cohen Matzliah

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.25 08:33:43