我先在網(wǎng)上找到了如下代碼
jquery 實現(xiàn) 單選框點擊取消
//單選按鈕再次點擊取消選中效果js
$("input[type='radio']").on('click', function() {
if ($(this).data('ischecked') == true) {
$(this).prop('checked', false);
$(this).data('ischecked', false);
} else {
$(this).prop('checked', true);
$(this).data('ischecked', true);
}
$(this).parents('.z-label').siblings('.z-label').find("input[type='radio']").data('ischecked', false);
});
但是發(fā)現(xiàn)會出現(xiàn)選擇其他選項時需要按兩下的情況。
應(yīng)該和我去掉了倒數(shù)第二行有關(guān),修改如下:
//解決單選框單擊取消問題
$("input[type='radio']").on('click', function () {
const radioId = $(this)[0].id;
if (($(this).data('ischecked') === true)&&(window.radioId===radioId)){
$(this).prop('checked', false);
$(this).data('ischecked', false);
} else {
$(this).prop('checked', true);
$(this).data('ischecked', true);
}
window.radioId=radioId;
});