Javascript 使用 jQuery 动态创建和“单击”链接
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/6505300/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Dynamically create and "click" a link with jQuery
提问by aidan
I want to dynamically create an <a href="mailto:...">
element, then "click" it. All without modifying the page.
我想动态创建一个<a href="mailto:...">
元素,然后“单击”它。全部无需修改页面。
I'm trying this:
我正在尝试这个:
$('<a href="mailto:[email protected]"> </a>').click();
...to no avail
……无济于事
采纳答案by Alex Korban
Clicking on a link means changing window.location, so how about
单击链接意味着更改 window.location,那么如何
window.location = "mailto:[email protected]";
回答by solipsicle
Its not jquery, but it works just fine.
它不是 jquery,但它工作得很好。
var link = document.createElement('a');
link.href = url;
document.body.appendChild(link);
link.click();
回答by jBelanger
To make it work with jQuery, you first need to select the DOM element inside the jQuery object.
要使其与 jQuery 一起使用,您首先需要选择 jQuery 对象内的 DOM 元素。
$('body').append('<a id="link" href="mailto:[email protected]"> </a>');
$('#link')[0].click();
Notice the [0]
注意 [0]
fiddle: https://jsfiddle.net/fkwhvvhk/
回答by KevinBui
.click()
work with a DOM, not jQuery object
.click()
使用 DOM,而不是 jQuery 对象
it should be:
它应该是:
$('<a href="mailto:[email protected]"></a>')[0].click();
回答by wdm
Try something like this...
尝试这样的事情......
Demo: http://jsfiddle.net/wdm954/xtTGX/1
演示:http: //jsfiddle.net/wdm954/xtTGX/1
$('.a').append('<a class="b" href="mailto:[email protected]"> </a>');
$('.b').click(function() {
window.location = $(this).attr('href');
}).click();
回答by Adam Hutchinson
why not just change the window location to the href of the link? Is there any specific reason you need to use a link?
为什么不只是将窗口位置更改为链接的 href ?您是否有任何特定原因需要使用链接?
Otherwise:
除此以外:
window.location = 'http://example.com';
回答by SubniC
Yo can create the tag this way:
您可以通过以下方式创建标签:
$('PARENT_TAG').append('<a id="dinamic_link" href="mailto:[email protected]"> </a>');
//Now click it
$('#dinamic_link').click();
HTH!
哼!
回答by genesis
$('#something').append('<a id="link" href="mailto:[email protected]"></a>');
$('#link').trigger('click');
回答by Abdul Kader
I would say you should consider adding the href to a container (mostly div) using .append() and call .click()
我会说你应该考虑使用 .append() 将 href 添加到容器(主要是 div)并调用 .click()
$('parent_div').append('<a id="link" href="mailto:[email protected]"> </a>');
//Now click it
$('#link').click();
回答by Gabriele Petrioli
It is not possible to simulate normal clicks. You can only trigger click
event handlers that have been bound to an element..
无法模拟正常点击。您只能触发click
已绑定到元素的事件处理程序。
As @Alex has posted,you can change the window.location
to achieve the same effect..
正如@Alex 所发布的,您可以更改window.location
以达到相同的效果..