使用jQuery动态获取单选按钮组名称 [英] Dynamically get radio button group name using jQuery
本文介绍了使用jQuery动态获取单选按钮组名称的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想问一下是否有一种方法可以动态获取单选按钮组名称,即通过使[name=some_variable]
优化以下两个单击功能.
I would like to ask if there is a way to get a radio button group name dynamically i.e. optimize the following 2 click functions into one by having [name=some_variable]
.
我尝试过:
$('input:radio').click(function() {
alert($('input:radio:checked').attr('name'));
});
但是它总是返回我单击的第一个单选按钮组的名称.
but it always returns me the name of the first radio button group clicked.
$(document).ready(function(){
$('input:radio[name=q1]').click(function() {
var ans1 = $('input[name=q1]:radio:checked').val();
getUserAnswer(1, ans1);
});
$('input:radio[name=q2]').click(function() {
var ans2 = $('input[name=q2]:radio:checked').val();
getUserAnswer(2, ans2);
});
});
<body>
<ol>
<li><p>Q1<br />
<input type="radio" id="q1A" name="q1" value="A" />Q1 A<br />
<input type="radio" id="q1B" name="q1" value="B" />Q1 B<br />
<input type="radio" id="q1C" name="q1" value="C" />Q1 C<br />
<input type="radio" id="q1D" name="q1" value="D" />Q1 D<br />
</p></li>
<li><p>Q2<br />
<input type="radio" id="q2A" name="q2" value="A" />Q2 A<br />
<input type="radio" id="q2B" name="q2" value="B" />Q2 B<br />
<input type="radio" id="q2C" name="q2" value="C" />Q2 C<br />
<input type="radio" id="q2D" name="q2" value="D" />Q2 D<br />
</p></li>
</ol>
</body>
推荐答案
$('input:radio').click(function() {
console.log($(this).attr('name'));
});
您要在点击时选择一组新元素,但是您需要当前元素的属性,因此,您需要使用'this'来引用它.
You are selecting new set of elements on click, but you need the attr of the current element so, you need to refer to it with 'this'
这篇关于使用jQuery动态获取单选按钮组名称的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文