在jQuery中查找激活时的单选按钮

Finding a radio button on activation in jQuery

本文关键字:单选按钮 激活 查找 jQuery      更新时间:2023-09-26

选择单选按钮1打印hello 1时,选择单选按钮2打印hello 2。我该怎么做?

<form name="form" id="form">
First Class<input name="seat_class" id="a1" type="radio" value="First Class">
        Second Class        <input name="seat_class" type="radio" value="Standard Class"
        </form>

试试这个:

<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.5.2/jquery.min.js" type="text/javascript"></script>
<script type="text/javascript">
$(document).ready(function () {
    $("#radio1, #radio2").change(function(event) {
        if($(this).is(':checked')) {
            alert($(this).data("text"));
        }
    });
});
</script>
<input type="radio" id="radio1" name="test" data-text="hello 1">
<input type="radio" id="radio2" name="test" data-text="hello 2">

首先,您需要对html:进行一些更改

<form name="form" id="form">
    First Class
    <input name="seat_class" id="a1" type="radio" value="First Class" />
    Second Class
    <input name="seat_class" type="radio" value="Standard Class" id="a2" />
    <!-- Adding id="a2" -->
</form>

然后,使用jQuery添加一个事件:

$(function () {
    $('#form>input[type=radio]').change(function () {
        switch ($(this).attr('id')) {
            case 'a1':
                alert ('Hello 1');
                break;
            case 'a2':
                alert ('Hello 2');
                break;
        }
    });
});

结果如下:http://jsfiddle.net/GPwXs/1/

我不太确定你是否想检查单选按钮是否被按下?或者你想在用户打开其中一个收音机时执行一个操作,无论哪种方式:

您可以通过只返回"选定"按钮来检查是否选择了任一收音机:

first  = $('#a1:selected');
second = $('#a2:selected');

选择收音机时执行操作:

$('#a1').change(function() {
  alert('foo');
});
$('#a2').change(function() {
  alert('bar');
});

@user760946。我想这就是你想要的。。jsfiddle.net