onchange 屬性(IntelliSense 不會提示)AutoPostBack="false" 避免觸發伺服器回傳<%@ Page Language="C#" %>
<html xmlns="https://www.w3.org/1999/xhtml">
<head runat="server">
<title>DropDownList 客戶端事件</title>
<script type="text/javascript">
function getDropDownList() {
var ddl = document.getElementById("<%=ddl1.ClientID%>");
var txt = ddl.options[ddl.selectedIndex].text;
var val = ddl.value;
alert("Text: " + txt + ", Value: " + val);
}
</script>
</head>
<body>
<form id="form1" runat="server">
<asp:DropDownList ID="ddl1" runat="server"
AutoPostBack="false"
onchange="getDropDownList();">
<asp:ListItem Text="選項一" Value="V1" Selected="True" />
<asp:ListItem Text="選項二" Value="V2" />
<asp:ListItem Text="選項三" Value="V3" />
</asp:DropDownList>
</form>
</body></html>
| 屬性 | 說明 |
|---|---|
ClientID | 伺服器控制項實際渲染的 HTML id,必須用 <%= %> 取得 |
AutoPostBack="false" | 關閉自動回傳,純前端處理 |
onchange | 原生 JS 事件,選項改變即觸發 |
掌握此技巧,即可在不觸發 PostBack 情況下豐富 DropDownList 互動體驗。