[英]Get radio button previous state Click event/Uncheck the radio if previously checked
如何查看單選按鈕是否已在click
事件中選中?
實際上我想要做的是,如果單擊的收音機以前被選中,並且用戶再次單擊同一個收音機,然后取消選中它。
但是下面的代碼總是評估 if 條件 t true :P
$('input.radiooption').click(function(g) {
if ($(this).is(":checked")) {
console.log("already checked, now uncheck it");
} else {
console.log("Not checked");
}
});
附言
問題是,當我單擊未選中的單選按鈕時,它會被選中
當我單擊已選中的按鈕時,它會被選中
所以,我想知道一種方法來確定click
事件中單選按鈕的先前狀態。
使用 temp 變量跟蹤先前的狀態:
var prv; var markIt = function(e) { if (prv === this && this.checked) { this.checked = false; prv = null; //allow seemless selection for the same radio } else { prv = this; } }; $(function() { $('input.radiooption').on('click', markIt); });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script> <input type='radio' name='group' class='radiooption' /> <input type='radio' name='group' class='radiooption' /> <input type='radio' name='group' class='radiooption' /> <input type='radio' name='group' class='radiooption' /> <input type='radio' name='group' class='radiooption' />
干得好:
var makeRadiosDeselectableByName = function(name){
$('input[name=' + name + ']').click(function() {
if($(this).attr('previousValue') == 'true'){
$(this).attr('checked', false)
} else {
$('input[name=' + name + ']').attr('previousValue', false);
}
$(this).attr('previousValue', $(this).attr('checked'));
});
};
這是完整的例子:http: //jsfiddle.net/EtNXP/1467/
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.