可以将文章内容翻译成中文,广告屏蔽插件可能会导致该功能失效(如失效,请关闭广告屏蔽插件后再试):
问题:
I'm trying to retrieve a server control in JavaScript. For testing purposes I am calling the JavaScript function from the page load event.
protected void Page_Load(object sender, EventArgs e){ ClientScript.RegisterClientScriptBlock(GetType(), "js", "confirmCallBack();", true); }
And my JavaScript function is
function confirmCallBack() { var a = document.getElementById('<%= Page.Master.FindControl("PlaceHolderContent").FindControl("Button1").ClientID %>'); var b = document.getElementById('<%=Button1.ClientID%>'); }
my problem is that both a and b return null. Even when I view the page source the correct ClientID is returned.
I should add that I'm using master page.
Any ideas.
回答1:
Gotcha!
You have to use RegisterStartupScript
instead of RegisterClientScriptBlock
Here My Example.
MasterPage:
<%@ Master Language="C#" AutoEventWireup="true" CodeBehind="MasterPage.master.cs" Inherits="prueba.MasterPage" %> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head runat="server"> <title></title> <script type="text/javascript"> function confirmCallBack() { var a = document.getElementById('<%= Page.Master.FindControl("ContentPlaceHolder1").FindControl("Button1").ClientID %>'); alert(a.value); } </script> <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>
WebForm1.aspx
<%@ Page Title="" Language="C#" MasterPageFile="~/MasterPage.Master" AutoEventWireup="true" CodeBehind="WebForm1.aspx.cs" Inherits="prueba.WebForm1" %> <asp:Content ID="Content1" ContentPlaceHolderID="head" runat="server"> </asp:Content> <asp:Content ID="Content2" ContentPlaceHolderID="ContentPlaceHolder1" runat="server"> <asp:Button ID="Button1" runat="server" Text="Button" /> </asp:Content>
WebForm1.aspx.cs
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; namespace prueba { public partial class WebForm1 : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { ClientScript.RegisterStartupScript(this.GetType(), "js", "confirmCallBack();", true); } } }
回答2:
Is Button1
visible? I mean, from the server side. Make sure Button1.Visible is true.
Controls that aren't Visible
won't be rendered in HTML, so although they are assigned a ClientID
, they don't actually exist on the client side.