實現效果:第一次點擊單選按鈕時選中該按鈕,再次點擊時取消選中該單選按鈕。
關鍵就是要將單選按鈕原來的值保存起來,第二次點擊時。如果原來選中則取消,否則選中。
看代碼吧,是用jQuery實現的,功能雖小。知識點不少啊。。。。。
- $(document).ready(function(){
- var old = null; //用來保存原來的對象
- $("input[name='sex']").each(function(){//循環綁定事件
- if(this.checked){
- old = this; //如果當前對象選中,保存該對象
- }
- this.onclick = function(){
- if(this == old){//如果點擊的對象原來是選中的,取消選中
- this.checked = false;
- old = null;
- } else{
- old = this;
- }
- }
- });
- });