使用 jQuery 动态获取单选按钮组名称 [英] Dynamically get radio button group name using jQuery

查看:20
本文介绍了使用 jQuery 动态获取单选按钮组名称的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想问是否有一种方法可以动态获取单选按钮组名称,即通过 [name=some_variable] 将以下 2 次单击功能优化为一个.

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆