使用母版页内的javascript访问母版页中的控件

时间:2010-09-16 12:19:49

标签: asp.net

如何使用javascript访问母版页中的控件?主页面包含一个搜索文本框,在控件的按键事件中,我调用了母版页内联的javascript函数。我在该javascript函数中获得了在文本框中输入的值。我试过提供document.getElementById(“<%= txtSearch.ClientID%>”)。value以及document.getElementById(“txtSearch”)。value。两者都显示错误。我必须从母版本本身访问文本框控件!

1 个答案:

答案 0 :(得分: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>