如何用jQuery获取单选按钮组中选中项的nth-child序号?
如何用jQuery获取选中单选按钮的nth-child序号?
我的HTML代码
<div class="form-check ml-4"> <input class="form-check-input" type="radio" name="1" id="1" value="First"> <label class="form-check-label" for="1">First</label> </div> <div class="form-check ml-4"> <input class="form-check-input" type="radio" name="1" id="2" value="Second"> <label class="form-check-label" for="2">Second</label> </div> <div class="form-check ml-4"> <input class="form-check-input" type="radio" name="1" id="3" value="Third"> <label class="form-check-label" for="3">Third</label> </div>
我试过的代码
下面这段代码没得到预期结果:
(($(find("input[type=radio]:checked")).attr('nth-child()')))
正确实现方法
你写的代码有两个明显问题:
find()用法错误,jQuery里不能单独直接调用find(),需指定上下文或直接使用选择器,比如$("input[type=radio]:checked")attr('nth-child()')逻辑错误,nth-child()是CSS选择器规则,并非元素的属性,无法用attr()方法获取
要拿到选中单选按钮对应的nth-child序号(从1开始计数),可以用以下两种方法:
方法一:基于父容器的位置
每个单选按钮都包裹在.form-check容器中,先找到选中按钮的父容器,再获取它在兄弟元素中的索引,最后加1(因为jQuery的index()返回值从0开始):
// 得到从1开始的序号 var selectedNum = $("input[type=radio][name='1']:checked").closest(".form-check").index() + 1; console.log(selectedNum);
方法二:直接基于单选按钮组
针对同name的所有单选按钮集合,找到选中项在该组内的位置,同样加1处理:
// 得到从1开始的序号 var radioGroup = $("input[type=radio][name='1']"); var selectedNum = radioGroup.index(radioGroup.filter(":checked")) + 1; console.log(selectedNum);
补充说明
- jQuery的
index()方法:默认返回元素在兄弟节点中的索引(从0开始);若传入jQuery对象,则返回该对象在当前集合中的位置(同样从0开始) - 由于CSS的
nth-child是从1开始计数,所以最终结果需要加1才能对应上
内容的提问来源于stack exchange,提问作者Stephen
相关产品推荐
相关产品推荐

