我不确定您要做什么。几乎所有其他答案都是关于index(),但在你的情况下,第二个单选按钮 index() 不会像你想要的那样返回 2 ,它会返回 1因为索引是基于 0 的。
这个 jsfiddle展示了如何获取特定组中选定输入的索引/值/分数/编号,以及如何汇总所有选定单选按钮的值。
<form id="myForm">
<h3>First Group</h3>
<input type="radio" name="group1" value="the-first" data-points="0">First</input>
<input type="radio" name="group1" value="the-second" data-points="20">Second</input>
<input type="radio" name="group1" value="the-third" data-points="300">Third</input>
<hr>
<h3>Second Group</h3>
<input type="radio" name="group2" value="four" data-points="4">4</input>
<input type="radio" name="group2" value="five" data-points="5">5</input>
<input type="radio" name="group2" value="six" data-points="6">6</input>
<hr>
<input type="submit" value="Submit" />
</form>
和 javascript/jQuery(出于演示目的使用 alert 而不是 console.log):
$(function () {
$("#myForm").submit(function () {
//This gets the checked input in group1
var g1 = $("input[name='group1']:checked");
alert("Group 1 \n Selected Value: " + g1.val() + " \n Selected Index: " + g1.index() + "\n Points: " + g1.data('points'));
var totalPoints = 0;
//This loops through all checked inputs
$.each($("input:checked"), function () {
totalPoints += $(this).data("points");
});
alert("Total points from all groups: " + totalPoints);
return false; //remove if you want to submit
});
});