如何根据单选框(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
相关产品推荐
相关产品推荐

