如何将一个侦听器附加到多个单选按钮? [英] How can I attach a listener to multiple radio buttons?
本文介绍了如何将一个侦听器附加到多个单选按钮?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有三个这样的单选按钮:
I have three radio buttons like this:
<input type="radio" name="P_1" value="1">Yes</input>
<input type="radio" name="P_1" value="2">No</input>
<input type="radio" name="P_2" value="1">Yes</input>
<input type="radio" name="P_2" value="2">No</input>
<input type="radio" name="P_3" value="1">Yes</input>
<input type="radio" name="P_3" value="2">No</input>
我正在尝试向每个单选按钮添加一个侦听器,以便在它们发生更改时得到通知.我正在做这样的事情:
I am trying to add a listener to each of these radio buttons so that I will be notified when they change. I am doing something like this:
for (var i = 1; i <= 3; i++) {
$("input[name='P_" + i + "']").live('change', function () {
doProcessing("P_" + i, $("input[name='P_" + i + "']:checked").val());
});
}
但是,这似乎不起作用.它调用doProcessing
并将i
设置为4,因为这是for循环结束时i
的值.在我的情况下,添加事件处理程序的正确方法是什么?
However, this does not seem to work. It calls doProcessing
with i
set to 4 because that is the value of i
at the end of the for loop. What is the correct way of adding an event handler in my case?
推荐答案
尝试
$('input:radio').on('change', function(){
//access value of changed radio group with $(this).val()
});
或者,如果您使用的是< jQuery 1.7
Or, if you're using < jQuery 1.7
$('input:radio').live('change', function(){
//do stuff with $(this).val()
});
这篇关于如何将一个侦听器附加到多个单选按钮?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文