如何在 Asp.net 中的 .cs 文件后面的代码中调用 javascript 函数

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/23541165/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-28 01:03:44  来源:igfitidea点击:

How to call javascript function in code behind .cs file in Asp.net

c#javascriptasp.net

提问by user3395635

I tried to call the function ApplyCSS() which is in my SearchPage.ascx page inside the Script tag and in .CS file I am trying to call that function using the below code:

我试图调用函数 ApplyCSS(),它位于我的 SearchPage.ascx 页面中的 Script 标签和 .CS 文件中,我试图使用以下代码调用该函数:

ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "Script", "ApplyCSS();", true);

but I am getting javascript runtime error object expected.

但我得到预期的 javascript 运行时错误对象。

回答by Erwin

The likely cause of this error is that ApplyCSS();isn't defined at the time when the function is called.

此错误的可能原因ApplyCSS();是在调用函数时未定义。

So, is the ApplyCSS();function defined in a .js file? If so, you have to go with this kind of approach:

那么,ApplyCSS();函数是在 .js 文件中定义的吗?如果是这样,你必须采用这种方法:

$(document).ready(function () { ApplyCSS(); } );

$(document).ready(function () { ApplyCSS(); } );

You'll need jQuery to do this

你需要jQuery来做到这一点

回答by Vikram

   <script type="text/javascript">
        function MyFunc(){
};
</script>


 ScriptManager.RegisterStartupScript(this, Page.GetType(), "key", "MyFunc()", true);

Semicolon is not required after MyFunc() Call. You can refer thislink

MyFunc() 调用后不需要分号。你可以参考这个链接

回答by user3395635

Have your script line is should be

有你的脚本行应该是

<script type='text/javascript' language="javascript">
//ApplyCSS();
</script>

and please check your function is does not threw any error.

并请检查您的功能是否没有引发任何错误。

and try with this

试试这个

ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "Script", "javascript:ApplyCSS();", true);