如何从主页的javascript函数访问用户控制页面下拉列表控件ID?



主页:

<%@ Register TagPrefix="A" TagName="AA" Src="~/UserControls/ab.ascx" %>
 <A:AA id="a1" runtat="server" />
 <asp:Button ID="btn" Visible="true" runat="Server" OnClick="Btn_Click" OnClientClick="javascript:PreLoad();" />
<script type="text/javascript">
function PreLoad() {
 var empty = '<%= (a1.FindControl("ddl")).ClientID %>'; 
// the above line giving error as 'ddl is inaccessible due to its protection level'
}
</script>

在用户控制页面中:

 <%@ ControlLanguage="C#" AutoEventWireup="true" CodeBehind="ab.ascx.cs" inherits="ab.ascx.designer.cs" %>
 <asp:DropDownList ID="ddl" runat="server"> </asp:DropDownList>

在ab.ascx.designer.cs

protected global::System.Web.UI.WebControls.DropDownList ddl;

有人请解释访问"PreLoad()"中的"ddl"的干净简单的正确方法javascript函数?

将标签更改为:

<asp:DropDownList ID="ddl" runat="server" ClientIDMode="static"> </asp:DropDownList>

这意味着控件将使用您指定的确切ID进行渲染。然后更改您的javascript以使用控件的确切id,并通过以下方式访问:

document.getElementById("ddl");

或者使用jQuery:

$("#ddl");

理想情况下,您也应该将此javascript代码移动到外部文件中。

最新更新