查找已选中的单选按钮的名称

Anu*_*lla -1 javascript jquery radio-button

我的页面有大约25个单选按钮组.当在组中选择单选按钮时,我想执行特定于该组的操作,因此需要无线电组的NAME属性.

Lix*_*Lix 6

以此HTML为例:

<div id="stackExchange">
  <input type="radio" name="sofu_group" value="Stack Overflow">
  <input type="radio" name="sofu_group" value="Meta Stack Overflow">
  <input type="radio" name="sofu_group" value="Server Fault">
  <input type="radio" name="sofu_group" value="Super User">
</div>
<!-- In no particular order - don't want to start a flame war ;) -->
Run Code Online (Sandbox Code Playgroud)

如果你想推断出点击的单选按钮所属的组,你可以使用这样的东西:

// jQuery ver 1.7+
$("#stackExchange input:radio").on('click',function(){   
  var groupName = $(this).attr('name');
  var groupElements = $(this).parent().find(":radio[name='"+groupName+"']");
});
Run Code Online (Sandbox Code Playgroud)

让我们看看这里发生了什么:

  • $("#stackExchange input:radio")-这个选择会发现我们所有的是的decendants输入射频元件的#stackExchange使用元素:radio选择.(链接到文档).
  • $(this).attr('name')- 这是我们提取name所选无线电元素的属性的地方.(在我们的例子中 - 这变成了sofu_group).
  • $(this).parent()- 在这种情况下,变量$(this)引用被单击的无线电元素 - 因此我们选择其父#stackExchange元素- 元素.
  • parent().find(":radio[name='"+groupName+"']") - 该行将找到元素中保存的所有单选按钮,其名称属性设置为'sofu_group'.

在示例中 - 变量$(this)引用被单击的无线电元素.