admin管理员组

文章数量:1401599

How could one trigger the default action/event of a HTML link (anchor element)? That is to use JavaScript/jQuery to "click" an existing HTML link, as if the user has clicked it.

Just using .click() does not seem to work.

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

For this HTML:

<a id="alink" href="" target="_blank">a link</a>

Example fiddle: /

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).

How could one trigger the default action/event of a HTML link (anchor element)? That is to use JavaScript/jQuery to "click" an existing HTML link, as if the user has clicked it.

Just using .click() does not seem to work.

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

For this HTML:

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

Example fiddle: http://jsfiddle/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).

Share Improve this question edited Aug 25, 2011 at 7:03 Qtax asked Aug 25, 2011 at 6:50 QtaxQtax 34k9 gold badges89 silver badges125 bronze badges 2
  • 1 See this: stackoverflow./questions/1694595/… – Digital Plane Commented Aug 25, 2011 at 7:02
  • @Digital Plane, thanks, didn't see that one before. Altho it it would be interesting to know if there are any changes on the matter, or it the answer "it can't be done" still applies even for the latest browsers (eg Chrome 13+). – Qtax Commented Aug 25, 2011 at 7:13
Add a ment  | 

4 Answers 4

Reset to default 2

You can trigger the click event using a simple trigger method in jQuery.

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

Beware though, that even in the event gets fired, the browser will not follow the link href. The only way to follow the href is to actually click it with the mouse yourself.

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 ment to his own post: You can use 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>

try this:

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

本文标签: javascriptHow to trigger the default actionevent of a HTML link (anchor element)Stack Overflow