且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

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

更新时间:2023-10-17 18:33:10

如果您的页面没有没有具有母版页,您为什么会认为有一个母版页呢?从呈现为HTML的母版页开始,任何事情都可以.
请解释!
If you''re having a page that does not have a master page why would you think there''d be anything from a master page rendered to HTML.
Please explain!


您好

作为一个例子..

我在主页上有一个按钮..

<div> <asp:Button ID="Button25" runat="server" Text="Master Button" /></div>

现在,在内容页面中,我有一个脚本和一个按钮

Hi

As an example..

I am having a button in master page..

<div> <asp:Button ID="Button25" runat="server" Text="Master Button" /></div>

Now in the content page I am having a script and a button

<asp:Content ID="BodyContent" runat="server" ContentPlaceHolderID="MainContent">
    <script type="text/javascript" language="javascript">
        function showMasterPageControlID(ctrlId){
            alert(document.getElementById(ctrlId).id);
        }
    </script>
    <asp:Button ID="Button1" runat="server" Text="Button" />
</asp:Content>



现在,我将脚本从后面的代码中分配给按钮单击事件,如下所示



Now I assign the script to the button click event from the code behind as follows

protected void Page_Load(object sender, EventArgs e)
{
    Button1.Attributes.Add("onclick", "showMasterPageControlID('" + this.Master.FindControl("Button25").ClientID + "')");
}



可以..

但是,如果要在page_load事件中访问主控件,则可能需要按如下方式插入脚本..



This works..

But if you want to access the master control at page_load event then you may need to inject the script as follows..

protected void Page_Load(object sender, EventArgs e)
 {

     ClientScript.RegisterStartupScript(this.GetType(), "Script1", "<script type='text/javascript'>document.getElementById('" + this.Master.FindControl("Button25").ClientID + "').value='Master Button Modified';</script>");
     //Button1.Attributes.Add("onclick", "showMasterPageControlID('" + this.Master.FindControl("Button25").ClientID + "')");
 }



要以这种方式设置多个控件,请使用字符串构建器来创建脚本文本,并从stringbuilder的toString方法获取文本.

使用ClientID属性,而不要使用您标识控件的方式.因为当html树层次结构更改时,该id容易更改.

希望这可以帮助



For setting multiple controls in that way use a string builder to create your script text and get the text from stringbuilder''s toString method.

Use the ClientID property instead of using the way you identify the controls. Because that id change easily when the html tree hierarchy alters.

Hope this helps


by using the following code can access the controls in masterpage from popup window
window.opener.document.getElementById('ctl00_ContentPlaceHolder1_txtWSalerate').value=mytool_array[5];