0

我的 HTML 代码如下所示:

   <div id="single"><br><br>
     1) effew<br>
     <input name="answer0" id="answer0" value="1" type="radio"> ewf
     <input name="answer0" id="answer0" value="2" type="radio"> avb
     </div>
     <div id="single"><br><br>
     2) fe<br>
     <input name="answer1" id="answer1" value="1" type="radio"> few
     <input name="answer1" id="answer1" value="2" type="radio"> eww
     <input name="answer1" id="answer1" value="3" type="radio"> tfs
     </div>

我想以 id 为单个迭代上述 div 标签,然后在每个 div 标签中以单个 id 获取选定单选按钮的值。编写的jQuery代码是:

$("input[name=single]").each( function() {
    var val = $('input[name=answer]:checked').val();
    alert(val);
});

上面的 jQuery 代码似乎不起作用。请。建议我该如何解决?

4

4 回答 4

5

HTML (请注意,我更改Id了,class因为不允许重复的 id

 <div class="single"><br><br>
      1) effew<br>
     <input name="answer0" id="answer0" value="1" type="radio"> ewf
     <input name="answer0" id="answer0" value="2" type="radio"> avb
 </div>
 <div class="single"><br><br>
     2) fe<br>
     <input name="answer1" id="answer1" value="1" type="radio"> few
     <input name="answer1" id="answer1" value="2" type="radio"> eww
     <input name="answer1" id="answer1" value="3" type="radio"> tfs
 </div>

JS

$("div.single input[type=radio]:checked").each( function() {
    alert(this.value);
});

jsFiddle 演示

于 2012-06-19T16:34:23.827 回答
2

试试这个 - http://jsfiddle.net/NfLwy/

$("div.single input:checked").each( function() {
    alert( $(this).val() );
});

并且id应该是独一无二的。替换为class

于 2012-06-19T16:32:04.593 回答
0

相同的 html 上不能存在相同的 ID,在这种情况下您应该使用 class。
这是演示。尝试一下:

HTML

<div class="single"><br><br>
     1) effew<br>
     <input name="answer0" id="answer0" value="1" type="radio" checked> ewf
     <input name="answer0" id="answer0" value="2" type="radio"> avb
</div>
<div class="single"><br><br>
     2) fe<br>
     <input name="answer1" id="answer1" value="1" type="radio"> few
     <input name="answer1" id="answer1" value="2" type="radio"> eww
     <input name="answer1" id="answer1" value="3" type="radio" checked> tfs
</div>​

JS:

 $("div.single input[type=radio]:checked").each( function() {
        var val = $(this).val();
        alert(val);
    });​
于 2012-06-19T16:43:18.757 回答
0

一个更简单的解决方案是

$('.single').on('click',function(e) {
            alert($($(this).find("input[type=radio]:checked")).attr('id'));
        });
于 2016-03-15T11:20:15.740 回答