如何从 C# PageLoad 调用 Javascript?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/6531817/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to call Javascript from C# PageLoad?
提问by CMMaung
I want to ask How to call javascript from C# page load. My Javascript is
我想问一下如何从 C# 页面加载调用 javascript。我的 Javascript 是
function Hide(lst) {
if (document.getElementById) {
var tabList = document.getElementById(lst).style;
tabList.display = "none";
return false;
} else {
return true;
}
}
and want to call from pageload
并想从页面加载调用
if (dtSuperUser(sLogonID).Rows.Count < 1)
{
//Call Javascript with parameter name tablist
}
thanks
谢谢
回答by Justin
Actually, you can use pageOnload event to do so. Like this.
实际上,您可以使用 pageOnload 事件来执行此操作。像这样。
protected void Page_Load(object sender, EventArgs e)
{
if (IsPostBack)
{
this.ClientScript.RegisterStartupScript(this.GetType(), "show", "<script>document.getElementById('Your element').style.display = 'block'</script>");
}
else
{
this.ClientScript.RegisterStartupScript(this.GetType(), "show", "<script>document.getElementById('Your element').style.display = 'hidden'</script>");
}
}
回答by jaywayco
RegisterStartupScript("Hide", string.Format(@"if (document.getElementById) {
var tabList = document.getElementById('{0}').style;
tabList.display = 'none';
return false;
} else {
return true;
}",lst));
Or if you already have the Javascript function rendered in the Markup
或者,如果您已经在标记中呈现了 Javascript 函数
RegisterStartupScript("Hide",string.Format("Hide('{0}');",lst));
回答by Грозный
String csName = "myScript";
Type csType = this.GetType();
// Get a ClientScriptManager reference from the Page class.
ClientScriptManager cs = Page.ClientScript;
// Check to see if the client script is already registered.
if (!cs.IsClientScriptBlockRegistered(csType, csName))
{
cs.RegisterClientScriptBlock(csType, csName,
string.Format("Hide({0})", lst.ClientID));
}
回答by Mark D
Are you using webforms or MVC? If using webforms check:
您使用的是 webforms 还是 MVC?如果使用网络表单检查:
http://msdn.microsoft.com/en-us/library/Aa479011
http://msdn.microsoft.com/en-us/library/Aa479011
Page.RegisterStartupScript("MyScript",
"<script language=javascript>" +
"function AlertHello() { alert('Hello ASP.NET'); }</script>");
Button1.Attributes["onclick"] = "AlertHello()";
Button2.Attributes["onclick"] = "AlertHello()";