ASP.NET WebForms 伺服器控制項(runat="server")渲染後的 id 屬性會被改寫為 ctl00_ContentPlaceHolder1_StoreName 這類長名稱,導致 jQuery 無法用原始 ID 選取。
| 方案 | 優點 | 缺點 | 適用版本 |
|---|---|---|---|
<%= Control.ClientID %> 內嵌 | 簡單、無額外標記 | JS 必須寫在 .aspx/.ascx 內、無法分離 .js 檔 | 所有版本 |
ClientIDMode="Static" | ID 固定不變、可直接用 #id | 開發者需自行確保唯一性、巢狀命名容器可能衝突 | ASP.NET 4.0+ |
ClientIDMode="Predictable" | 可預測命名規則 | 仍較長 | ASP.NET 4.0+ |
CSS 類別選擇器 .class | 完全分離 JS/CSS、不依賴 ID | 同頁面多個同類控制項需額外區分 | 所有版本 |
資料屬性 data-control="storename" | 語意化、穩定、可多實例 | 需手動加屬性 | 所有版本 |
<asp:TextBox ID="StoreName" runat="server" ClientIDMode="Static" CssClass="form-control" />
<asp:Label ID="Label5" runat="server" ClientIDMode="Static" Text="真實的店鋪名稱..." />
// 獨立 .js 檔可直接使用
$('#StoreName').focus(function() {
$('#Label5').text('請輸入真實的店鋪名稱').css('color', '#666');
});
<script>
window.myApp = window.myApp || {};
myApp.controls = {
storeName: '<%= StoreName.ClientID %>',
label5: '<%= Label5.ClientID %>'
};
</script>
// 獨立 .js
$('#' + myApp.controls.storeName).focus(...);
<asp:TextBox ID="StoreName" runat="server" CssClass="js-store-name" />
<asp:Label ID="Label5" runat="server" CssClass="js-store-name-hint" />
$('.js-store-name').focus(function() {
$('.js-store-name-hint').text('請輸入...').css('color', '#666');
});
data-* 屬性標記(最推薦無 ClientIDMode 時)<asp:TextBox ID="StoreName" runat="server" data-role="store-name-input" />
<asp:Label ID="Label5" runat="server" data-role="store-name-hint" />
$('[data-role="store-name-input"]').focus(function() {
$('[data-role="store-name-hint"]').text('請輸入...').css('color', '#666');
});
<asp:GridView ID="gv" runat="server" ClientIDMode="Predictable" ClientIDRowSuffix="ProductID">
<Columns>
<asp:TemplateField>
<ItemTemplate>
<input type="hidden" name="pid" value='<%# Eval("ProductID") %>' />
<button class="btn-edit" data-id='<%# Eval("ProductID") %>'>編輯</button>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
// JS 端
$(document).on('click', '.btn-edit', function() {
const productId = $(this).data('id'); // 直接取 data-id
// 呼叫 API 編輯
});
重點:不要依賴 GridView 產生的 ID,改用 data-* 屬性攜帶業務鍵值。