获取 Jquery 中单选按钮组的 ID

get the id of radio button group in Jquery

本文关键字:ID 单选按钮 Jquery 获取      更新时间:2023-09-26

我有一组名为"periodType"的单选按钮。该组中有一个单选按钮的行为方式与其他按钮相同,除了它显示一个额外的div。我如何知道何时选中该特定单选按钮,因为下面的更改函数对于组中的所有单选按钮都非常通用:

  $('input[name="periodType"]').change(function() {
        if(this.checked) {
            //do something (for all radio buttons)
            //If unique radio button also do this
        }
    }); 
    <input type="radio" name="periodType" default>
<input type="radio" name="periodType" default>
<input type="radio" name="periodType" default>
<input type="radio" name="periodType" default>

您可能希望为无线电输入添加一个值:

<input type="radio" name="periodType" value="one" default>
<input type="radio" name="periodType" value="two" default>
<input type="radio" name="periodType" value="three" default>
<input type="radio" name="periodType" value="four" default>

然后查询该值:

$('input[name="periodType"]').change(function() {
  if (this.value == 'three' && this.checked) {
    //do something (for all radio buttons)
    //If unique radio button also do this
  }
}); 
$('input[name="periodType"]').change(function() {
        if(this.checked) {
            //do something (for all radio buttons)
            //If unique radio button also do this
           var idval = $(this).attr("id");
           if (idval == "something")
           {
             //do something
            }
        }
    });

也许你正在寻找这样的东西。我将每个收音机添加到其自己的div中,只是为了显示更改时的行为。如果您有任何问题,请告诉我。


    <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
            "http://www.w3.org/TR/html4/loose.dtd">
    <html>
    <head>
        <title></title>
        <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
        <style type="text/css">
            .selected{background-color: #fad42e;}
            .notSelected{background-color: #6f6e73;}
        </style>
        <script type="text/javascript">

            $(document).ready(function () {

                $('input[name="periodType"]').change(function() {
                    $(this).parent('div').removeClass();
                    $(this).parent('div').addClass('selected');
                    $('input[name="periodType"]')
                            .parent('div')
                            .not($(this).parent("div"))
                            .each(function(e){
                                $(this).removeClass();
                                $(this).addClass("notSelected");
                            });
                });

            });


        </script>
    </head>
    <body>
    <div>
        <input type="radio" name="periodType" >
    </div>
    <div>
        <input type="radio" name="periodType" >
    </div>
    <div>
        <input type="radio" name="periodType" >
    </div>
    <div>
        <input type="radio" name="periodType" >
    </div>
    </body>
    </html>