Html 如何使用 JavaScript 调用 asp:Button OnClick 事件?

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

How to call a asp:Button OnClick event using JavaScript?

javascriptasp.nethtml.net

提问by jorame

I have a question, I have a button like below:

我有一个问题,我有一个像下面这样的按钮:

<asp:Button ID="savebtn" runat="server" OnClick="savebtn_Click" Visible="false" />

I then have HTML button like like below:

然后我有如下所示的 HTML 按钮:

<button id="btnsave" onclick="fncsave">Save</button>

I have the javascript below:

我有下面的javascript:

<script type="text/javascript">
     function fncsave()
     {
        document.getElementById('<%= savebtn.OnClick %>').click()
     }
</script>

My question now is, how can I call the asp:Button OnClick from the HTML button? I have read you can do this by calling from JavaScript by Id but is not working.

我现在的问题是,如何从 HTML 按钮调用 asp:Button OnClick?我读过你可以通过 Id 从 JavaScript 调用来做到这一点,但它不起作用。

Any help will be really appreciate it.

任何帮助将不胜感激。

Thank you

谢谢

回答by Sunny

Set style= "display:none;". By setting visible=false, it will not render button in the browser. Thus,client side script wont execute.

设置 style= "display:none;"。通过设置visible=false,它不会在浏览器中呈现按钮。因此,客户端脚本不会执行。

<asp:Button ID="savebtn" runat="server" OnClick="savebtn_Click" style="display:none" />

html markup should be

html 标记应该是

<button id="btnsave" onclick="fncsave()">Save</button>

Change javascript to

将 javascript 更改为

<script type="text/javascript">
     function fncsave()
     {
        document.getElementById('<%= savebtn.ClientID %>').click();
     }
</script>

回答by Glenn Ferrie

If you're open to using jQuery:

如果您愿意使用 jQuery:

<script type="text/javascript">
 function fncsave()
 {
    $('#<%= savebtn.ClientID %>').click();
 }
</script>

Also, if you are using .NET 4 or better you can make the ClientIDMode == staticand simplify the code:

此外,如果您使用 .NET 4 或更高版本,您可以制作ClientIDMode == static并简化代码:

<script type="text/javascript">
 function fncsave()
 {
    $("#savebtn").click();
 }
</script>

Reference: MSDN Article for Control.ClientIDMode

参考:MSDN 文章 Control.ClientIDMode