ASP.NET RadioButton 伺服端 ID 為 RadioButton1,但渲染到瀏覽器的 HTML id 屬性通常被 NamingContainer 前綴修改 (如 ctl00_ContentPlaceHolder1_RadioButton1),導致 document.getElementById("RadioButton1") 找不到元素。
// ASPX
<asp:RadioButton ID="RadioButton1" runat="server" />
// 渲染後 HTML (範例)
<input id="ctl00_MainContent_RadioButton1" type="radio" name="ctl00$MainContent$RadioButton1" />
// JS 錯誤
document.getElementById("RadioButton1") // null
<asp:RadioButton ID="RadioButton1" runat="server" ClientIDMode="Static" />
// 渲染 id="RadioButton1",JS 直接用 "RadioButton1"
<script>
var rb1Id = '<%= RadioButton1.ClientID %>';
var rb2Id = '<%= RadioButton2.ClientID %>';
function shows(...) {
if (document.getElementById(rb1Id).checked) { ... }
}
</script>
<asp:RadioButton ID="RadioButton1" runat="server" CssClass="myRadio" />
<asp:RadioButton ID="RadioButton2" runat="server" CssClass="myRadio" />
<script>
var radios = document.querySelectorAll('.myRadio');
radios.forEach(function(r) { if (r.checked) { ... } });
</script>
var $rb1 = $('#<%= RadioButton1.ClientID %>');
// 或屬性開頭匹配
var $rb = $('input[id$="_RadioButton1"]');
Panel 也是 INamingContainer,會進一步增加前綴層級,更加劇 ID 不確定性。方案二、三、四均不受影響。
建議:新專案啟用 ClientIDMode="Predictable" (站點級) 配合方案二輸出關鍵 ID,舊專案用方案三 Class 選擇器最穩健。