javascript 单选按钮组 - 按钮的更改事件被取消选择?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3337818/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Radio button group - change events for buttons become deselected?
提问by morgancodes
Let's say I have a group of two radio buttons:
假设我有一组两个单选按钮:
<input type="radio" name="radioButtonGroup" value="button1" checked="true"/>
<input type="radio" name="radioButtonGroup" value="button2"/>
It seems that clicking the second button triggers an event handler on that button only. However, the first button does become deselected, and visually does change. Can anyone verify that events are fired onlyon the button that was selected, and not any of the other buttons in the group which become deselected as a result of the click? Any clever ways to watch a radio button for a deselecting event?
似乎单击第二个按钮只会在该按钮上触发事件处理程序。但是,第一个按钮会被取消选择,并且视觉上会发生变化。任何人都可以验证事件是否仅在选定的按钮上触发,而不是组中因单击而取消选择的任何其他按钮?任何聪明的方法来观看取消选择事件的单选按钮?
回答by Yash
Although it cannot be confirmed, but the event change triggers don't happen on the entire group.
虽然无法确认,但事件变更触发不会发生在整个组上。
If you want that to happen, you can do it using various JS libraries like jQuery, YUI, etc. or even plain javascript, as follows:
如果你希望发生这种情况,你可以使用各种 JS 库,如 jQuery、YUI 等,甚至是普通的 javascript,如下所示:
function buttonGroupChange(){
var radioElements = document.getElementsByName("radio_group_name");
for(var i = 0; i < radioElements.length; i++){
if(radioElements[i].checked == true){
//do something
}
else{
//do something
}
}
}
This function can be called on the onClick or the onChange event.
可以在 onClick 或 onChange 事件上调用此函数。
I hope that solves your problem.
我希望这能解决你的问题。
回答by Troy Alford
Firstly, it is important to note that a "Click" event on any of the radios fires AFTER the "checked" value is already updated. This is important - because it means you can't detect the previous item once the event is already fired. If you Cancel the event, you are actually changing the value BACK - not stopping it initially. This is important to how you approach the problem.
首先,需要注意的是,在“checked”值已经更新后,任何收音机上的“Click”事件都会触发。这很重要 - 因为这意味着一旦事件已经被触发,你就无法检测到前一个项目。如果您取消事件,您实际上是在更改值 BACK - 最初并没有停止它。这对您处理问题的方式很重要。
Example:
例子:
<input type="radio" name="radioButtonGroup" value="button1" checked="true"/>
<input type="radio" name="radioButtonGroup" value="button2"/>
// At this point, the ':checked' item is button1.
$('input[type=radio]').bind('click', function (ev) {
// If you click on button2 - by this point, the ':checked' item is already button2.
ev.preventDefault(); // These two lines will stop the radio from actually
ev.stopPropagation(); // changing selection.
// At this point, the ':checked' item is set BACK to button1.
});
Because of this, the easiest solution is to track the "last" selected item in a closure alongside your event handlers, as follows:
因此,最简单的解决方案是在事件处理程序旁边跟踪闭包中的“最后一个”选定项,如下所示:
<input type="radio" name="radioButtonGroup" value="button1" checked="true"/>
<input type="radio" name="radioButtonGroup" value="button2"/>
<script type="text/javascript">
var $last = $('[name=radioButtonGroup]:checked');
// Select the radio buttons as a group.
var $radios = $('[name=radioButtonGroup]').bind('change', function (ev) {
// Click event handler
var $clicked = $(ev.target); // This is the radio that just got clicked.
$last.trigger('unclick'); // Fire the "unclick" event on the Last radio.
$last = $('[name=radioButtonGroup]:checked'); // Update the $last item.
// Should see the clicked item's "Value" property.
console.log("Clicked " + $clicked.attr('value'), $clicked, ev);
}).bind('unclick', function (ev) {
// Handler for our new "unclick" event.
// - fires whenever a radio loses focus.
var $unclicked = $(ev.target); // The radio losing it's checked status.
// Should see the unclicked item's "Value" property.
console.log("Unclicked " + $unclicked.attr('value'), $unclicked, ev);
});
</script>
For a working example, see:
有关工作示例,请参阅:
回答by Troy Alford
The simple nature of the radio button set is that only one button can be selected at a time. Selecting a button automatically means the others are not selected, but there is no specific action for deselecting. Therefore, you only need to worry about the one event, because it affects all the buttons in the set at one time.
单选按钮集的简单性质是一次只能选择一个按钮。自动选择一个按钮意味着没有选择其他按钮,但没有取消选择的特定操作。因此,您只需要担心一个事件,因为它会同时影响集合中的所有按钮。
If you would like to use an element that allows for multiple selections try checkboxes.
如果您想使用允许进行多项选择的元素,请尝试使用复选框。
回答by Pat
I can't confirm that an event is only fired for the selected button, but if you needed to do something with the button that was just deselected, the following would work:
我无法确认是否仅针对所选按钮触发了事件,但是如果您需要对刚刚取消选择的按钮执行某些操作,则以下操作将起作用:
$(document).ready(function(){
var selectedRadio = null;
$("input:radio").change(function(){
if(selectedRadio != null){
alert(selectedRadio.val());
}
selectedRadio = $(this);
});
});
In action here.
在这里行动。
If you need to keep track of multiple groups of radio buttons, you could do it with an array of currently selected buttons and match within that array when a change is detected.
如果您需要跟踪多组单选按钮,您可以使用当前选定按钮的数组来完成,并在检测到更改时在该数组中进行匹配。
回答by Aram Alipoor
If you are using jQuery, you can bind and trigger a custom event which we name it deselect.
如果您正在使用jQuery,您可以绑定并触发我们命名为 的自定义事件deselect。
Using code below we define the deselectevent.
使用下面的代码定义deselect事件。
$(document).ready(function(){
var selectedRadioList = {};
$('input:radio:checked').each(function(){
selectedRadioList[this.name] = this;
});
$('input:radio').click(function(){
if(selectedRadioList[this.name])
$(selectedRadioList[this.name]).trigger('deselect');
selectedRadioList[this.name] = this;
});
});
And now we can bind to deselectevery where we need.
现在我们可以绑定到deselect我们需要的每一个地方。
$(document).ready(function(){
$('input:radio').on('deselect', function(){
alert('radio `' + this.value + '` has been deselected');
});
});

