首先,重要的是要注意,任何無線電的「點擊」事件在「檢查」值已經更新後觸發。這很重要 - 因爲這意味着一旦事件已經被觸發就無法檢測到前一個項目。如果您取消該事件,則實際上正在更改BACK的值 - 而不是最初停止它。這對你如何解決問題很重要。
例子:
<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.
});
正因爲如此,最簡單的方法是跟蹤一個封閉旁邊的事件處理程序的「最後」選擇項,具體如下:
<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>
對於工作例如,參見:
http://jsfiddle.net/TroyAlford/wvrtC/
請選擇一個正確的答案,或指定你需要什麼進一步的信息來解決你的問題。 – 2012-09-07 17:18:02