2010-03-19 50 views
6

如何获取选中使用jQuery的RadioButton索引?我需要阅读并保存到饼干以后使用的代码加载状态jQuery RadioButton索引

$('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" /> 

问候 托马斯

回答

7

这将返回选定的单选按钮

$('input[name=compression]:checked').index() 

的从零开始指数的情况下描述在注释使用中(通常使用正确的语法)

$('input[name=porient]:checked').index('input[name=porient]') 

如果你想知道为什么第一个给出错误的结果。如果没有参数传递给 的.index()方法,你应该阅读.index() documentation

,返回值是 指示的位置的整数 jQuery 对象相对于其同级元素 元素中的第一个元素。

在问题的示例中,没有任何“其他”兄弟姐妹,但您的单选按钮。因此它起作用。

在从注释中<br />标签是单选按钮的兄弟姐妹,因此样本是指数1这就是为什么你认为index()给出了错误的位置

+0

奇怪的东西,它的工作原理上的“压缩”单选按钮精上面列出了哪些代码,但是在下面的代码中,“porient”单选按钮会返回错误的索引。如果选择第一个单选按钮,则返回0(ok),然后返回2(!!!!)无法理解发生了什么。有任何想法吗?

<输入名称= “porient” 类型= “无线电” 的值= “纵向” 检查= “检查”/>肖像
<输入名称= “porient” 类型= “无线电” 的值= “风景”/ >风景

Tomas 2010-03-19 08:30:06

+0

查看扩展的答案 – jitter 2010-03-19 08:40:44