0

在加载时,我会调用 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);
}
4

1 回答 1

1

您可以在面板和隐藏它的代码隐藏处显示您的标记吗?

Visible将属性设置为 false 和将 style属性设置为 none之间是有区别display的——第一个根本不会渲染元素,这意味着没有使用您要查找的 id 渲染任何内容。

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

尝试做

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

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

edit: you also need to actually get a reference to the control. you're passing the id string to ToggleAlert, which relays it to HideControl, which is expecting an object not a string.

function HideControl(_c) { // _c is the id of the element
    var control = document.getElementById(_c);
    if (control != null)
        control.style.display = 'none';
}
于 2010-06-25T19:47:35.753 回答