更改单选按钮状态更改时的标题

时间:2016-04-11 06:31:21

标签: javascript html css

如果选中按钮,如何更改单选按钮的标题和标签文字?这就是我的代码的样子,但当我按下按钮时没有任何反应。虽然我认为这段代码是正确的:

<script type='text/javascript' src="https://code.jquery.com/jquery-  1.12.1.min.js">
$(function () {
// when the radio changes
$(':radio.radio').on('change', function(e) {
// set text of h1 element
$('h1').text('mmmmm');
});
});

</script>
<h1 style='color:black;font-family:"Courier New", monospace;margin-left:-10px;' id='h1'>#1.Question 1</h1>
<div>

                <div>
                        <input type="radio" name="radio" id="radio2" class="radio"/>
                        <label for="radio2" style="color:black;font-family:impact;text-align:center;" id='2'>Answer 1</label>
                </div>

                <div>   
                        <input type="radio" name="radio" id="radio3" class="radio"/>
                        <label for="radio3" style="color:black;font-family:impact;text-align:center;" id='3'>Answer 2</label>
                </div>

                <div>   
                        <input type="radio" name="radio" id="radio4" class="radio"/>
                        <label for="radio4" style="color:black;font-family:impact;text-align:center;" id='4'>Answer 3</label>
                </div>

1 个答案:

答案 0 :(得分:0)

尝试这样的事情:

$(':radio.radio').each(function(){
$(this).change(function(){
if($(this).attr('id') == 'radio2'){
$(this).siblings('label').text('Answer 1 selected');
$('h1').text('Answer 1 is selected');
} else if ($(this).attr('id') == 'radio3'){
$(this).siblings('label').text('Answer 2 selected');
$('h1').text('Answer 2 is selected');
} else if ($(this).attr('id') == 'radio4') {
$(this).siblings('label').text('Answer 3 selected');
$('h1').text('Answer 3 is selected');
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<h1 style='color:black;font-family:"Courier New", monospace;margin-left:-10px;' id='h1'>#1.Question 1</h1>
<div>

                <div>
                        <input type="radio" name="radio" id="radio2" class="radio"/>
                        <label for="radio2" style="color:black;font-family:impact;text-align:center;" id='2'>Answer 1</label>
                </div>

                <div>   
                        <input type="radio" name="radio" id="radio3" class="radio"/>
                        <label for="radio3" style="color:black;font-family:impact;text-align:center;" id='3'>Answer 2</label>
                </div>

                <div>   
                        <input type="radio" name="radio" id="radio4" class="radio"/>
                        <label for="radio4" style="color:black;font-family:impact;text-align:center;" id='4'>Answer 3</label>
                </div>