[英]Call ButtonClick() Event
My event is never being fired, and I can not figure out owhy. 我的活动从未被解雇,我无法弄清楚。 Here is my syntax
这是我的语法
<asp:Button id="btnone" runat="server" visible="false" OnClick="btnone_Click" />
<script type="text/javascript">
$( document ).ready(function() {
var button = document.getElementById('btnone').click();
}
});
And for my C# code behind 对于我后面的C#代码
protected void btnone_Click(object sender, EventArgs e)
{
Response.Write("It was clicked through JS");
}
EDIT I have also tried to use this code to capture the ClientID of the button but it's not working 编辑我也曾尝试使用此代码来捕获按钮的ClientID,但它不起作用
$( document ).ready(function () {
$('<%= btnone.ClientID %>').click();
}
});
First of all you should set ClientIDMode="Static". 首先,您应该设置ClientIDMode =“ Static”。 Otherwise there will be no element with ID 'btnone'.
否则,将没有ID为“ btnone”的元素。 Also, if you set visible="false" - it does not apply style "display:none;".
另外,如果您设置visible =“ false”-它不会应用样式“ display:none;”。 Instead button won't be on the page.
而是按钮不会在页面上。 You can use this code:
您可以使用以下代码:
.aspx : .aspx:
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="WebForm1.aspx.cs" Inherits="WebApplication2.WebForm1" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
<script src="//code.jquery.com/jquery-1.12.0.min.js"></script>
<script type="text/javascript">
$( document ).ready(function() {
var button = document.getElementById('btnone').click();
});
</script>
<style>
#btnone
{
display:none;
}
</style>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:Button id="btnone" runat="server" ClientIDMode="Static" OnClick="btnone_Click" Text="btn"/>
</div>
</form>
</body>
</html>
.cs : .cs:
namespace WebApplication2
{
public partial class WebForm1 : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void btnone_Click(object sender, EventArgs e)
{
Response.Write("It was clicked through JS");
}
}
}
First of all, you need to put the property ClientIDMode="Static"
in your button, this grants the ID will be the same in runtime, it's what you need to get in Javascript. 首先,您需要在按钮中放入属性
ClientIDMode="Static"
,这将授予ID在运行时相同,这是您需要在Javascript中获得的。
In jQuery you need to do something like this: 在jQuery中,您需要执行以下操作:
$( document ).ready(function() { // Getting the event in a callback $('#btnone').click(function(){ // Work here.. }); // Trigger the event $('#btnone').click(); });
If you want to work in pure JS try something like this: 如果要使用纯JS,请尝试以下操作:
$( document ).ready(function() { // Here is the callback when the event is triggered function getTheClick(){ // Work here.. } // Assigning the event and it's callback document.getElementById("btnone").addEventListener("click", getTheClick); });
In this case you need to assign a function to an event using the AddEventListener function. 在这种情况下,您需要使用AddEventListener函数将函数分配给事件。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.