使用 jquery 单击或更改单选中的事件

我有一些无线电在我的网页,我想做的事情时,检查无线电的变化,但代码不工作的 IE:

$('input:radio').change(...);

在谷歌搜索之后,人们建议使用 点击代替,但是它不起作用。

这是示例代码:

<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.5.1/jquery.min.js"></script>
<script type="text/javascript">
$('document').ready(
function(){
$('input:radio').click(
function(){
alert('changed');
}
);
}
);


</script>
</head>
<body>
<input type="radio" name="testGroup" id="test1" />test1<br/>
<input type="radio" name="testGroup" id="test2" />test2<br/>
<input type="radio" name="testGroup" id="test3" />test3</br>
</body>
</html>

它也不工作在 IE。

所以我想知道发生了什么?

我还担心,如果我点击一个选中的收音机,它是否会重新触发更改事件?

更新:

我不能添加评论,所以我在这里回复。

我使用 IE8和链接 Furqan 给我也不工作在 IE8。我不知道为什么..。

209461 次浏览

This code worked for me:

$(function(){


$('input:radio').change(function(){
alert('changed');
});


});

http://jsfiddle.net/3q29L/

Try

$(document).ready(

instead of

$('document').ready(

or you can use a shorthand form

$(function(){
});

You can specify the name attribute as below:

$( 'input[name="testGroup"]:radio' ).change(

Works for me too, here is a better solution::

fiddle demo

<form id="myForm">
<input type="radio" name="radioName" value="1" />one<br />
<input type="radio" name="radioName" value="2" />two
</form>


<script>
$('#myForm input[type=radio]').change(function() {
alert(this.value);
});
</script>

You must make sure that you initialized jquery above all other imports and javascript functions. Because $ is a jquery function. Even

$(function(){
<code>
});

will not check jquery initialised or not. It will ensure that <code> will run only after all the javascripts are initialized.

$( 'input[name="testGroup"]:radio' ).on('change', function(e) {
console.log(e.type);
return false;
});

This syntax is a little more flexible to handle events. Not only can you observe "changes", but also other types of events can be controlled here too by using one single event handler. You can do this by passing the list of events as arguments to the first parameter. See jQuery On

Secondly, .change() is a shortcut for .on( "change", handler ). See here. I prefer using .on() rather than .change because I have more control over the events.

Lastly, I'm simply showing an alternative syntax to attach the event to the element.