網(LieHuo.Net)教程 最近在做項目的時要實現單項選擇的功能,用RadioButtonList剛好可以實現。但是遺憾的是RadioButtonList選擇后不能取消。所以自己用Javascript來實現取消選擇的功能。
首先,定義一個全局的數組變量,保存選擇狀態。
以下為引用的內容: //保存各選項選擇的狀態 var arrayChecked = new Array(); |
然后,注冊 onload="InitChecked()"事件 ,初始化數組。這一步的目的在于加載原來已經保存過的選項時,保證其狀態為選中。
以下為引用的內容: //初始化選擇狀態 function InitChecked() { var controlID = 'radioEmpRole1'; var table = document.getElementById(controlID); if (table) { radioButtonList = table.getElementsByTagName('input'); for (var i = 0; i < radioButtonList .length; i++) { if (radioButtonList .item(i).checked) { radioButtonList [i] = 1; //被選中 } else { radioButtonList [i] = 0; //未被選中 } } } } |
最后,為RadioButtonList注冊 onclick="Checked()" 事件,選擇選項時根據選項狀態和歷史狀態來決定選項是否被取消選擇。
以下為引用的內容: //設置選擇狀態 function Checked() { var controlID = 'radioEmpRole1'; var table = document.getElementById(controlID); if (table) { radioButtonList = table.getElementsByTagName('input'); for (var i = 0; i < radioButtonList .length; i++) { if (radioButtonList .item(i).checked) { //此次點擊,該選項被選中,則判斷此選項的歷史狀態,若也是被選中,則會取消選擇。 if (arrayChecked[i] == 1) { radioButtonList .item(i).checked = false; arrayChecked[i] = 0; } else { arrayChecked[i] = 1; } } else { arrayChecked[i] = 0; } } } } |
通過以上三步,就可以實現點擊被選擇的選項時會取消選擇。