LinkBut​​ton不会在click()上调用

为什么这不起作用?

  $(document).ready(function() { $('.myButton').click(); });    
Click

您要提交表单,还是添加Click事件? 您的链接按钮转换为

 Click 

,所以它没有点击式JavaScript。 因此, .click(); 什么也没做。
我没有测试它,但也许这会工作:

 eval($('.myButton').attr('href')); 

触发器(’click’)触发jQuery的click事件监听器,.NET没有连接到它。 您可以触发javascript click事件,该事件将转到(或在此情况下运行)href属性中的内容:

  $('.myButton')[0].click(); 

要么

  ($('.myButton').length ? $('.myButton') : $(''))[0].click(); 

如果您不确定该按钮是否会出现在页面上。

如果需要触发链接按钮的OnClick服务器端事件,则需要使用__doPostback(eventTarget,eventArgument)。

例如:

   

您需要指定一个事件处理程序,以便在引发click事件时触发

  $(document).ready(function() { $('.myButton', '#form1') .click(function() { /* Your code to run when Click event is raised. In this case, something like window.location = "http://..." This can be an anonymous or named function */ return false; // This is required as you have set a PostbackUrl // on the LinkButton which will post the form // to the specified URL }); }); 

我已经使用ASP.NET 3.5对上面的内容进行了测试,它按预期工作。

Linkbutton上还有OnClientClick属性,它指定在引发click事件时要运行的客户端脚本。

我可以问你想要达到的目标吗?

click事件处理程序必须实际执行操作。 试试这个:

 $(function () { $('.myButton').click(function () { alert('Hello!'); }); }); 

你需要给linkBut​​ton一个CssClass =“myButton”,然后在顶部使用它

 $(document).ready(function() { $('.myButton').click(function(){ alert("hello thar"); }); }); 

这是一个艰难的。 据我了解,你想模仿点击javascript代码中的按钮的行为。 问题是ASP.NET为onclick处理程序添加了一些花哨的javascript代码。

在jQuery中手动触发事件时,只会执行jQuery添加的事件代码,而不是onclick属性或href属性中的javascript。 因此,我们的想法是创建一个新的事件处理程序,它将执行属性中定义的原始javascript。

我要提出的建议尚未经过测试,但我会试一试:

 $(document).ready(function() { // redefine the event $(".myButton").click(function() { var href = $(this).attr("href"); if (href.substr(0,10) == "javascript:") { new Function(href.substr(10)).call(this); // this will make sure that "this" is // correctly set when evaluating the javascript // code } else { window.location = href; } return false; }); // this will fire the click: $(".myButton").click(); }); 

只是为了澄清,只有FireFox会遇到这个问题。 请参阅http://www.devtoolshed.com/content/fix-firefox-click-event-issue 。 在FireFox中,anchor(a)标签没有click()函数,允许JavaScript代码直接模拟它们上的点击事件。 它们允许您映射锚标记的click 事件 ,而不是使用click()函数来模拟它。

幸运的是,ASP.NET将JavaScript回发代码放入href属性中,您可以在其中获取它并在其上运行eval。 (或者只是调用window.location.href = document.GetElementById(’LinkBut​​ton1’)。href;)。

或者,你可以调用__doPostBack(’LinkBut​​ton1’); 请注意,“LinkBut​​ton1”应替换为LinkBut​​ton的ClientID / UniqueID以处理命名容器,例如UserControls,MasterPages等。

乔丹·里格