javascript 如何使用按钮调用javascript函数和代码
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/15692880/
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 function and code behind using button
提问by mayil
How to call javascript function and code behind function using button?
如何使用按钮调用javascript函数和函数背后的代码?
<asp:button id="btnSave" onclick="btnSave();" onclientclick ="return javascriptfunction();" runat="server">
</asp:button>
I tried like this too. but no response.
我也这样试过。但没有回应。
<asp:button id="btnSave" onclick="btnSave();" onclientclick ="return true;" runat="server">
</asp:button>
even, javascript function return true, its not calling codebehind function. May i know reason?
甚至,javascript 函数返回 true,它不调用代码隐藏函数。我可以知道原因吗?
回答by Win
The code should be something like this -
代码应该是这样的 -
JavaScript:
JavaScript:
<script>
function save()
{
return confirm('Are you sure you want to continue?');
}
</script>
ASPX:
ASPX:
<asp:Button ID="btnSave" OnClick="btnSave_Click" OnClientClick="return save();"
runat="server" />
C# CodeBehind:
C# 代码隐藏:
protected void btnSave_Click(object sender, EventArgs e)
{
// Do something
}
It basically call JavaScript function before posting back to server. Whether post back to server or not is depending upon the return
value from JavaScript function.
它基本上在回发到服务器之前调用 JavaScript 函数。是否回发到服务器取决于return
来自 JavaScript 函数的值。
Button control's OnClick
is an server side event so you need to attach to server side click event.
按钮控件OnClick
是服务器端事件,因此您需要附加到服务器端单击事件。
回答by Vortex
The best way I have found to do this is from code behind using RegisterStartupScript
我发现做到这一点的最好方法是使用 RegisterStartupScript 从背后的代码中
ScriptManager.RegisterStartupScript(this, this.GetType(), "name", "javascriptfunction();", true);