使用jQuery以编程方式单击 link

问题描述 投票:59回答:9

我知道之前曾有人问过这个问题,但是在网上搜索后,我似乎找不到直接的答案。

HTML

<a id=myAnchor href=index.php>

jQuery(这两个都不起作用)

 $('#myAnchor').click();

$('#myAnchor').trigger('click');

最简单,最有效的方法是什么?

jquery hyperlink click anchor
9个回答
96
投票

尝试一下:

$('#myAnchor')[0].click();

它对我有用。


33
投票
window.location = document.getElementById('myAnchor').href

25
投票

单击只是触发单击事件,而不是实际的“ goto-the-links-href”操作。

您必须编写自己的处理程序,然后您的[[$('#myAnchor')。trigger('click');才能起作用...

$("#myAnchor").click(function(event) { var link = $(this); var target = link.attr("target"); if($.trim(target).length > 0) { window.open(link.attr("href"), target); } else { window.location = link.attr("href"); } event.preventDefault(); });

4
投票
<a href="#" id="myAnchor">Click me</a> <script type="text/javascript"> $(document).ready(function(){ $('#myAnchor').click(function(){ window.location.href = 'index.php'; }); }) </script>

4
投票
onclick="window.location = this.href"添加到<a>元素。进行此修改后,可以.click()以预期的行为进行。为此,您可以在页面上的每个链接上添加以下内容:

<script type="text/javascript"> $(function () { $("a").attr("onclick", "window.location = this.href"); }); </script>


4
投票
我尝试了上述几种解决方案,但它们对我没有用。这是对我有用的页面的链接automatically click a link

上面的链接有很多解决方案,这是对我有用的解决方案,

<button onclick="fun();">Magic button</button> <!--The link you want to automatically click--> <a href='http://www.ercafe.com' id="myAnchor">My website</a>

现在在<script>标记内,

<script> function fun(){ actuateLink(document.getElementById('myAnchor')); } function actuateLink(link) { var allowDefaultAction = true; if (link.click) { link.click(); return; } else if (document.createEvent) { var e = document.createEvent('MouseEvents'); e.initEvent( 'click' // event type ,true // can bubble? ,true // cancelable? ); allowDefaultAction = link.dispatchEvent(e); } if (allowDefaultAction) { var f = document.createElement('form'); f.action = link.href; document.body.appendChild(f); f.submit(); } } </script>

复制粘贴上面的代码,然后单击'Magic button'按钮,您将被重定向到ErCafe.com

0
投票
如果您使用的是jQuery,则可以使用jQuery.trigger http://api.jquery.com/trigger/]来做到这一点>

示例

<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title></title> <script type="text/javascript" src="https://code.jquery.com/jquery-2.2.3.js"></script> </head> <body> <a id="foo" onclick="action()"></a> <script type="text/javascript"> function action(){ window.location.replace("http://stackoverflow.com/q/9081426/5526354") } $("#foo").trigger("click"); </script> </body> </html>


0
投票
尝试此操作以获得兼容性;

0
投票
我有类似的问题。试试这个$('#myAnchor').get(0).click();这对我有用
© www.soinside.com 2019 - 2024. All rights reserved.