ASP.NET `RadioButtonList` 與 `CheckBoxList` 渲染為 `
// 實體類別 public class FivePhase { public int ID { get; set; } public string Name { get; set; } public FivePhase() { } public FivePhase(int id, string name) { ID = id; Name = name; } } // 後端綁定邏輯 private List GetFivePhases() { return new List { new FivePhase(1, "木"), new FivePhase(2, "火"), new FivePhase(3, "土"), new FivePhase(4, "金"), new FivePhase(5, "水") }; } protected void Page_Load(object sender, EventArgs e) { if (!IsPostBack) { rblPhases.DataSource = GetFivePhases(); rblPhases.DataTextField = "Name"; rblPhases.DataValueField = "ID"; rblPhases.DataBind(); } }
<asp:RadioButtonList ID="rblPhases" runat="server" RepeatDirection="Horizontal"></asp:RadioButtonList> <!-- 或 CheckBoxList --> <asp:CheckBoxList ID="cblPhases" runat="server" RepeatDirection="Horizontal"></asp:CheckBoxList>
<style> .phase-label { cursor: pointer; padding: 4px 8px; transition: all 0.2s; } .phase-label:hover, .phase-label.overStyle { font-weight: bold; color: #e74c3c; background: #fef9e7; border-radius: 4px; } .phase-label.outStyle { font-weight: normal; color: #2c3e50; background: transparent; } </style>
<script> // 通用函式:為指定控件的所有 label 掛載 hover 效果 function bindListHover(listClientId) { const container = document.getElementById(listClientId); if (!container) return; // 使用事件委派:只在容器掛一個 mouseover/mouseout container.addEventListener('mouseover', e => { const label = e.target.closest('label'); if (label) label.classList.add('overStyle'); }); container.addEventListener('mouseout', e => { const label = e.target.closest('label'); if (label) label.classList.remove('overStyle'); }); } // 頁面載入後初始化 document.addEventListener('DOMContentLoaded', () => { bindListHover('<%= rblPhases.ClientID %>'); bindListHover('<%= cblPhases.ClientID %>'); }); </script>
若控件在 `UpdatePanel` 內,非同步回發後 DOM 會重建,需重新綁定:
function bindListHover(listClientId) { ... } // 同上 // 全域函式供 PageRequestManager 呼叫 function rebindAllHovers() { bindListHover('<%= rblPhases.ClientID %>'); bindListHover('<%= cblPhases.ClientID %>'); } // 初始綁定 document.addEventListener('DOMContentLoaded', rebindAllHovers); // UpdatePanel 回發後重新綁定 if (typeof Sys !== 'undefined' && Sys.WebForms.PageRequestManager) { Sys.WebForms.PageRequestManager.getInstance().add_endRequest(rebindAllHovers); }
<table id="rblPhases"> <tr> <td><input id="rblPhases_0" type="radio" name="rblPhases" value="1" /><label for="rblPhases_0">木</label></td> <td><input id="rblPhases_1" type="radio" name="rblPhases" value="2" /><label for="rblPhases_1">火</label></td> ... </tr> </table>
JS 透過 `closest('label')` 精準找到使用者滑過的標籤,切換 CSS 類別即可實現視覺回饋,無需修改伺服端代碼,符合關注點分離原則。
技術架構概覽 本範例示範在傳統 ASP.NET Web Fo
為什麼選擇 MySQL? 開源免費、社群活躍、跨平台支援完
問題背景 固定結構的 GridView 需顯示不同題型的試題
C# ref 與 out 關鍵字深度解析:值類型與參考類型的