使用 jQuery 动态获取单选按钮组名称
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/5577238/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Dynamically get radio button group name using jQuery
提问by gisc
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]
.
我想问一下是否有办法动态获取单选按钮组名称,即通过将[name=some_variable]
.
I tried:
我试过:
$('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>
回答by Headshota
$('input:radio').click(function() {
console.log($(this).attr('name'));
});
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'
您正在单击时选择一组新元素,但您需要当前元素的属性,因此,您需要使用“this”来引用它
回答by David says reinstate Monica
Something like the following should work:
像下面这样的东西应该工作:
$('input').click(function() {
var thisName = $(this).attr('name');
var qNum = thisName.substring(1);
? ? var ans2 = $('input[name=' + thisName + ']:radio:checked').val();
? ? getUserAnswer(thisName, ans2);
});