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
4 Answers
Reset to default 2You 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
版权声明:本文标题:javascript - How to trigger the default actionevent of a HTML link (anchor element)? - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1744235989a2596555.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论