2010-09-16 111 views
0

如何使用javascript訪問母版頁中的控件?母版頁由一個搜索文本框組成,在控件的關鍵事件上,我調用母版頁內嵌的javascript函數。我在那個javascript函數中獲得了在文本框中輸入的值。我試着給document.getElementById(「<%= txtSearch.ClientID%>」)。value以及document.getElementById(「txtSearch」).value。兩者都顯示錯誤。我必須從母版頁本身訪問文本框控件!在母版頁中使用javascript在母版頁中訪問控件

+0

你得到了什麼錯誤?什麼瀏覽器版本? – 2010-09-16 12:25:29

+0

我正在使用IE 8瀏覽器。指定此代碼時document.getElementById(「txtSearch」).value;我在瀏覽器中將'object required error'作爲客戶端錯誤消息。並指定document.getElementById(「<%= txtSearch.ClientID%>」)。值我得到'源代碼不可用'警告消息,並在單擊確定時,它顯示服務器端錯誤'Controls集合不能被修改,因爲該控件包含代碼塊(即<% ... %>)。' – banupriya 2010-09-16 12:29:40

+0

我指定了document.getElementById(「ct100_txtSearch」).value。只是一個臨時修復!但是任何人都請建議如何使用代碼動態獲取此ID。我通過查看生成的頁面的源代碼來獲得此信息。 – banupriya 2010-09-17 09:55:20

回答

1

我認爲您在評論中顯示的內容中缺少一些重要的標記。我試過了,下面的代碼工作。檢查一下,也許你會看到你的問題在哪裏;否則,請解釋您的標記在哪裏不同。

<%@ Master Language="C#" AutoEventWireup="true" CodeBehind="Site.master.cs" Inherits="WebApplicationDummy.SiteMaster" %> 

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> 
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en"> 
<head runat="server"> 
    <title></title> 
    <script type="text/javascript"> 
     function txtSearch_KeyDown() { 
      alert(document.getElementById('<%=txtSearch.ClientID %>').value); 
     } 
    </script> 
</head> 
<body> 
    <form runat="server"> 
    <table width="226" border="0" cellpadding="2" cellspacing="2"> 
     <tr> 
      <td width="150" align="right"> 
       <asp:TextBox ID="txtSearch" CssClass="para1Black" Width="180px" ValidationGroup="GlobalSearch" 
        runat="server" MaxLength="100" onkeydown="txtSearch_KeyDown()"></asp:TextBox> 
      </td> 
      <td width="62"> 
       <asp:ImageButton ID="imgbtnSearch" ToolTip="Click to search." ImageUrl="images/search2.jpeg" 
        CausesValidation="true" Width="22px" Height="22px" runat="server" ValidationGroup="GlobalSearch" /> 
      </td> 
     </tr> 
    </table> 
    <asp:ContentPlaceHolder ID="MainContent" runat="server" /> 
    </form> 
</body> 
</html>