jQuery RadioButton索引

Tom*_*mas 6 indexing jquery radio-button

如何使用jQuery检查RadioButton索引?我需要阅读它并保存到cookie以便稍后使用代码加载状态

$('input[name="compression"]')[{Reading from cookies code}].checked = true;



1<input name="compression" type="radio" value="1" checked="checked" />
2<input name="compression" type="radio" value="2" />
3<input name="compression" type="radio" value="3" />
Run Code Online (Sandbox Code Playgroud)

关心托马斯

jit*_*ter 7

这将返回所选单选按钮的从零开始的索引

$('input[name=compression]:checked').index()
Run Code Online (Sandbox Code Playgroud)

对于注释使用中描述的情况(通常使用正确的语法)

$('input[name=porient]:checked').index('input[name=porient]')
Run Code Online (Sandbox Code Playgroud)

如果你想知道第一个给出错误结果的原因,你应该阅读.index()文档

如果没有将参数传递给.index()方法,则返回值是一个整数,指示jQuery对象中第一个元素相对于其兄弟元素的位置.

在问题的样本中,没有任何"其他"兄弟姐妹,而是你的无线电按钮.因此它有效.

在评论的样本中,<br />标签是radiobuttons的兄弟,因此在索引1上.这就是为什么你认为index()给出了错误的位置