【问题标题】:asp.net external JavaScript file doesn't find Control.ClientIDasp.net 外部 JavaScript 文件找不到 Control.ClientID
【发布时间】:2010-06-25 19:21:42
【问题描述】:

在加载时,我会调用 JavaScript setTimeout() 函数来隐藏 .NET 面板控件,并在首次加载时将其隐藏在代码中。单击保存按钮会将面板设置为可见,然后重新加载页面,此时调用 setTimeout() 函数...所以基本上您单击保存,然后看到一个带有“已保存详细信息”的面板三秒钟,此时它消失。

问题是外部 JavaScript 文件找不到 _pDivAlert.ClientID(我已经调试过,它返回 null)。它仅在代码位于 .aspx 页面的标记中时才有效。关于如何将客户端 ID 传递给 HideControl() 函数或从外部 JS 文件中找到 ClientID 的任何建议?

这是我的代码,有什么建议吗?

<script language="javascript" src="Forms.js" type="text/javascript"></script>

<body onload="ToggleAlert()">
<form id="form1" runat="server">
<script type="text/javascript">
    //alert the user that the details were saved
    function HideControl() {
        var control = document.getElementById('<%=_pDivAlert.ClientID %>');
        if(control != null)
            control.style.display = 'none';
    }
    function ToggleAlert() {
        setTimeout("HideControl()", 3000);
    }
</script>

我也尝试在 ToggleAlert() 调用中发送 ClientID,但没有成功:

<body onload="ToggleAlert('<%=_pDivAlert.ClientID %>')">

外部 JS:

function HideControl(_c) {
var control = _c;
if (control != null)
    control.style.display = 'none';
}
function ToggleAlert(_c) {
    setTimeout("HideControl(_c)", 3000);
}

【问题讨论】:

    标签: asp.net javascript clientid


    【解决方案1】:

    你能用面板和代码隐藏显示你的标记吗?

    Visible 属性设置为false 和将样式display 属性设置为none 之间存在区别——第一个根本不会呈现元素,这意味着没有任何内容与您正在查看的id 一起呈现为。

    编辑:这可能是因为您在超时时调用HideControl 的方式 - 这应该是一个函数而不是一个字符串。

    试试看

    function ToggleAlert(_c) {
        setTimeout( 
            function () { 
                HideControl(_c); 
            }, 3000);
    }
    

    为了清楚起见,当您将字符串传递给setTimeout 时,它会被评估然后运行。 eval 生成的代码块将在与您的 ToggleAlert 方法不同的范围内运行,因此 _c 届时将不可用。

    编辑:您还需要实际获取对控件的引用。您将 id 字符串传递给 ToggleAlert,后者将其中继到 HideControl,它需要一个对象而不是字符串。

    function HideControl(_c) { // _c is the id of the element
        var control = document.getElementById(_c);
        if (control != null)
            control.style.display = 'none';
    }
    

    【讨论】:

    • 感谢您的回复。我将 HideControl() 设为了一个函数,现在我在外部 JS 中看到了控件 ID。但是现在在调试时,我看到“control.style.display = 'none'”中的“样式”是“未定义的”。
    猜你喜欢
    • 2016-06-28
    • 1970-01-01
    • 1970-01-01
    • 2013-06-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多