使用客户端 JavaScript 在 X 秒后自动隐藏 ASP.NET 2.0 控制






3.63/5 (5投票s)
2005年9月29日

51518
这段代码将遍历页面上的所有控件,找到您想要隐藏的类型(例如,单击“提交”按钮后的状态标签),并在 X 秒后使用 JavaScript 隐藏它们。
引言
我需要一种方法来在几秒钟后隐藏一个 ASP.NET Label
控件。我有一个页面,用户可以在文本框中输入一些文本,单击“提交”,然后显示一个标签“已保存!”——我希望该标签在几秒钟后消失,以防用户想要编辑文本并再次保存,从而在几秒钟内再次显示保存的标签。
没什么太复杂的,只是 VB 代码,它遍历页面上的所有控件,查找 ID 的前几个字符与“lblStatus”或“lblSaved”匹配的 Label
控件,然后编写 JavaScript 代码块在几秒钟后隐藏这些控件。
我将这段代码应用于一个名为“commonFunctions
”的类中,并在我的母页的 Load
事件中调用它
commonFunctions.hideAllStatusLabelsAfterXSecs(Page)
希望这段代码不难理解,您可以根据自己的需要进行修改。它可以应用于任何类型的控件,而不仅仅是 Label
。
Public Shared Function hideAllStatusLabelsAfterXSecs(ByVal mePage As Page)
' hide all "lblStatus" and "lblSaved" labels after X seconds
' based on this javascript:
' <script type='text/javascript'>
' if (document.getElementById('control_id') != null)
' var x1 = setTimeout("document.getElementById('control_id').
' style.display='none'", 2000);
' </script>
' ^^ control_id is control.ClientID in ASP.NET 2.0 code
' # of seconds until hide
Dim xsecs As Integer = 2
' convert request seconds into js seconds
Dim realSecs As Integer = xsecs * 1000
' define the script string to add to the page
Dim theScript As New StringBuilder
' js header
theScript.Append("<script type='text/javascript'>" + vbCrLf)
theScript.Append("// hide all status labels after X seconds" + vbCrLf)
' iterate through all page controls
Dim oControl As Control
Dim childc As Control
Dim labelall As Label
Dim countControls As Integer = 0
Dim jsCtrlStr As String ' document.getElementByID('ctrl_id')
For Each oControl In mePage.Form.Controls
For Each childc In oControl.Controls
' is it a label?
If TypeOf childc Is Label Then
labelall = CType(childc, Label)
' is it a label we want to hide after X seconds?
If Left(childc.ID.ToString, 9) = "lblStatus" Or _
Left(childc.ID.ToString, 8) = "lblSaved" Then
' increment variable so no two vars are the same in js
countControls = countControls + 1
' define js control string
jsCtrlStr = "document.getElementById('" & _
childc.ClientID & "')"
' is the control currently visible? script error otherwise
theScript.Append("if (" & jsCtrlStr & " != null) ")
' rest of js
theScript.Append("var x" & countControls.ToString & _
" = setTimeout(""" & jsCtrlStr & _
".style.display='none'"", " & _
realSecs.ToString & ");" + vbCrLf)
End If
End If
Next
Next
' js close block
theScript.Append("</script>")
'test: show client js block, stop
'System.Web.HttpContext.Current.Response.Write(theScript.ToString)
'System.Web.HttpContext.Current.Response.End()
' add js block to page
mePage.ClientScript.RegisterStartupScript(GetType(String), _
"HideLabelControls", theScript.ToString)
Return "0"
End Function