建议的方法是为要放置在您正在呈现的网页中的此类脚本添加特定的内容占位符控件。查看以下主/内容页面标记:
母版页:
<%@ Master Language="C#" AutoEventWireup="true" CodeBehind="Site1.master.cs" Inherits="WebApp.PageMethods.Site1" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
<asp:ContentPlaceHolder ID="head" runat="server">
</asp:ContentPlaceHolder>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:ContentPlaceHolder ID="ContentPlaceHolder1" runat="server">
</asp:ContentPlaceHolder>
</div>
</form>
</body>
</html>
有一个内容占位符head
,其中我必须编写一些 js 函数来尝试访问其他内容占位符中的下拉列表ContentPlaceHolder1
。
内容页面标记:
<%@ Page Title="" Language="C#" MasterPageFile="~/Site1.Master" AutoEventWireup="true" CodeBehind="WebForm3.aspx.cs" Inherits="WebApp.PageMethods.WebForm3" %>
<asp:Content ID="Content1" ContentPlaceHolderID="head" runat="server">
<script>
function foo() {
var ddl = document.getElementById('<%= DropDownList1.ClientID %>');
}
</script>
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="ContentPlaceHolder1" runat="server">
<asp:DropDownList ID="DropDownList1" runat="server"></asp:DropDownList>
</asp:Content>
在这里,我不必担心尝试访问嵌套在ContentPlaceHolderID
.
或者,如果您没有该选项/自由,您可以随时在母版页本身中编写如下内容:
var d = document.getElementById('<%= this.ContentPlaceHolder1.FindControl("DropDownList1").ClientID %>');