You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Site.Master中C#调用JS隐藏元素,刷新后重现的问题及解决

问题描述

我在Site.Master.cs中运行以下C#后台代码:

ScriptManager.RegisterStartupScript(this.Page, Page.GetType(), "text", "myFunction()", true);

这段代码会触发Site.Master.ASPX中的如下脚本:

<script>
        function myFunction() {
            var x = document.getElementById("XXXX");
            x.style.display = "none";
        }
</script>

目标是隐藏以下元素:

<li ID="XXXX" runat="server" ClientIDMode="Static"><a runat="server" href="~/Home">Home</a></li>

但我发现元素只会隐藏几毫秒,页面刷新后又重新显示了。请问怎么才能让该元素在刷新后保持隐藏状态?

已解决方案

经过思考与测试,我找到了可行的解决办法:将<li>元素移出LoggedInTemplate(因为在该模板内无法通过C#直接访问控件),然后在母版页的C#代码中设置控件的Visible属性,代码示例如下:

protected void Page_Init(object sender, EventArgs e)
{
    if ((System.Web.HttpContext.Current.User != null) && System.Web.HttpContext.Current.User.Identity.IsAuthenticated)
    {
        //MessageBox.Show("已认证");
        Aprobacionesbtn.Visible = true;    //导航栏中的按钮
        Reportesmenu.Visible = true;    //导航栏中的下拉菜单
    }
    else if ((System.Web.HttpContext.Current.User == null))
    {
        //MessageBox.Show("未认证");
        Aprobacionesbtn.Visible = false;    //导航栏中的按钮
        Reportesmenu.Visible = false;    //导航栏中的下拉菜单
    }
}

内容的提问来源于stack exchange,提问作者Emmanuel_InfTech

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.03 16:01:00