Dynamically create and “click” a link with jQuery

僤鯓⒐⒋嵵緔 提交于 2019-12-03 05:34:52

Clicking on a link means changing window.location, so how about

window.location = "mailto:test@test.com";

Its not jquery, but it works just fine.

var link = document.createElement('a');
link.href = url;
document.body.appendChild(link);
link.click();    

To make it work with jQuery, you first need to select the DOM element inside the jQuery object.

$('body').append('<a id="link" href="mailto:test@test.com">&nbsp;</a>');
$('#link')[0].click();

Notice the [0]

fiddle: https://jsfiddle.net/fkwhvvhk/

Try something like this...

Demo: http://jsfiddle.net/wdm954/xtTGX/1

$('.a').append('<a class="b" href="mailto:test@test.com">&nbsp;</a>');
$('.b').click(function() {
    window.location = $(this).attr('href');
}).click();

.click() work with a DOM, not jQuery object

it should be:

$('<a href="mailto:test@test.com"></a>')[0].click();

Yo can create the tag this way:

$('PARENT_TAG').append('<a id="dinamic_link" href="mailto:test@test.com">&nbsp;</a>');
//Now click it
$('#dinamic_link').click();

HTH!

why not just change the window location to the href of the link? Is there any specific reason you need to use a link?

Otherwise:

window.location = 'http://example.com';
$('#something').append('<a id="link" href="mailto:test@yourdomain.com"></a>');
$('#link').trigger('click');

I would say you should consider adding the href to a container (mostly div) using .append() and call .click()

$('parent_div').append('<a id="link" href="mailto:test@test.com">&nbsp;</a>');
//Now click it
$('#link').click();
Gabriele Petrioli

It is not possible to simulate normal clicks. You can only trigger click event handlers that have been bound to an element..

As @Alex has posted, you can change the window.location to achieve the same effect..

Just been doing a tutorial on this!

$("[href='mailto:test@test.com']").click();

This should select all elements with a href attribute with "mailto:test@test.com" as its value.

www.w3schools.com/jquery/jquery_selectors.asp

var link = document.createElement('<a>')
link.href = "mailto:test@test.com";
link.id = "hitme"
$('#hitme').click();

you have to use .on and then call .click . Dynamically generated hyper reference does not work with simple .click()

I have been found some problems with similar issue and I found the simplest way for me:

    var link = document.createElement('a');

    link.download = 'profile.png';
    link.href = '...';
    link.id = 'example';
    link.class = '...';

    document.body.appendChild(link);

    link.click();

In my case I lost a lot of time trying to do this with jquery, doing $('#example').click()but does not work for me. At least the problem was jquery, I did it without it. I hope that it can be help for somenone. Is a simple way to set an anchor to download an image and do click just after.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!