2012-01-13 93 views
4

我试图在JavaScript中检索服务器控件。出于测试目的,我从页面加载事件调用JavaScript函数。ASP.NET document.getElementById('<%= Control.ClientID%>');返回null

protected void Page_Load(object sender, EventArgs e){ 
    ClientScript.RegisterClientScriptBlock(GetType(), "js", "confirmCallBack();", true); 
} 

我的JavaScript函数是

function confirmCallBack() { 
    var a = document.getElementById('<%= Page.Master.FindControl("PlaceHolderContent").FindControl("Button1").ClientID %>'); 
    var b = document.getElementById('<%=Button1.ClientID%>'); 
} 

我的问题是,无论是A和B返回NULL。即使当我查看页面源时,也会返回正确的ClientID。

我应该补充说我正在使用母版页。

任何想法。

+0

我也会尽力去完成你想要什么,但对于一个快速的答案,为什么不您尝试通过页面加载中的参数传递Id? confirmCallBack(Button1.ClientID); – 2012-01-13 01:18:15

+0

简单的答案是不要使用自动生成的ASP ids – Raynos 2012-01-13 01:20:41

回答

8

嘿!

你必须使用RegisterStartupScript而不是RegisterClientScriptBlock

这里我举的例子。

母版:

<%@ 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); 

     } 
    } 
} 
+0

非常感谢。我被困在那里已有好几年了。 – user346443 2012-01-13 01:35:47

+0

感谢人,就像我之前的用户一样,我被困在这上面好几个小时。我正在接近把我的头发撕掉:0。 – Banzboy 2015-07-08 00:56:18

0

是否可见Button1?我的意思是,从服务器端。确保Button1.Visible为真。

不是Visible的控件将不会以HTML格式呈现,因此尽管它们被分配了ClientID,但它们实际上并不存在于客户端。

+0

有什么方法可以获得隐形asp.net控件的ID吗? – 2016-10-12 06:44:42

+0

@DKR ClientID属性为您提供_would_将赋予其在页面上呈现的控件_if_的ID。否则这些信息在客户端几乎是无用的。 – Humberto 2016-10-14 14:16:15

相关问题