简体   繁体   English

如何触发HTML链接(锚元素)的默认操作/事件?

[英]How to trigger the default action/event of a HTML link (anchor element)?

How could one trigger the default action/event of a HTML link (anchor element)? 如何触发HTML链接(锚元素)的默认操作/事件? That is to use JavaScript/jQuery to "click" an existing HTML link, as if the user has clicked it. 那就是使用JavaScript / jQuery来“单击”现有的HTML链接,就像用户已单击它一样。

Just using .click() does not seem to work. 仅使用.click()似乎不起作用。

$('#alink').click();
// the nothing happening

For this HTML: 对于此HTML:

<a id="alink" href="http://google.com" target="_blank">a link</a>

Example fiddle: http://jsfiddle.net/dCfD8/ 小提琴示例: http : //jsfiddle.net/dCfD8/

I'd rather not create a new window in JavaScript (and take care of whatever else needs to be handled when a link is clicked). 我宁愿不使用JavaScript创建一个新窗口(并注意单击链接时需要处理的所有其他内容)。

You can trigger the click event using a simple trigger method in jQuery. 您可以使用jQuery中的简单trigger方法来触发click事件。

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

Beware though, that even in the event gets fired, the browser will not follow the link href. 但是请注意,即使在事件被触发的情况下,浏览器也不会遵循链接href。 The only way to follow the href is to actually click it with the mouse yourself. 遵循href的唯一方法是自己亲自用鼠标单击它。

As far as I know, there is no way to force a link to behave as if it were clicked. 据我所知,没有办法强制链接表现为被单击。 You have to change the document location or something like that to actually navigate between pages. 您必须更改文档位置或类似的内容才能在页面之间实际导航。

Expanding on Fabio Cicerchia's comment to his own post: You can use window.open : 扩展Fabio Cicerchia对他自己的帖子的评论:您可以使用window.open

var link = $('#alink');
var target = link.attr("target");
window.open(link.attr("href"), target ? target : "_self");
    <script src='jquery lib source' ></script>
    <script>
    function force()
    {    ...do something...to fill page2
         $('#gopage2').trigger('submit');
    }    
    </script>  
    <form action='#page2' id='gopage2'>
    </form>

    ...
    <span name='#page2'>This is page2</span>

尝试这个:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM