参见英文答案 >
Download image with JavaScript2个
我有一个href和下载属性的链接:
我有一个href和下载属性的链接:
- <a id="lnk" href="data:text/csv;charset=utf-8,1%2C2%2C3" download="my_file.csv">click to download</a>
当我点击它(例如在Chrome中)时,会按照假设下载csv文件“my_file.csv”.
现在我希望能够以编程方式引发此操作.所以使用JQuery我试图做:
- $('#lnk').click();
要么
- $('#lnk').trigger("click");
但是没有下载该文件.
这是代码:
http://jsbin.com/yereg/3/edit
我可以从链接复制链接地址,然后只使用window.open:
- window.open('data:text/csv;charset=utf-8,1%2C2%2C3');
但这样我就无法设置文件名(链接通过download =“my_file.csv”属性).如果有办法设置文件名,这个解决方案很好.
备注:在我的情况下,应支持Chrome和Firefox.我不关心其他浏览器.
解决方法
来自jquery文档:
The click event is only triggered after this exact series of events:
The mouse button is depressed while the pointer is inside the element.
The mouse button is released while the pointer is inside the element.
您可以通过调用JavaScript本机事件
- $('#lnk').get(0).click();
或者更安全:
- var lnk = document.getElementById('lnk');
- if (lnk) {
- lnk.click();
- }
编辑:
出于好奇,我查看了jQuery源代码是如何完成的.事实证明,它们特意故意阻止链接上的浏览器的本机点击事件,请参阅最新jQuery版本(2.1.x)中events.js的以下摘录,尤其是注释:
- click: {
- [...]
- // For cross-browser consistency,don't fire native .click() on links
- _default: function( event ) {
- return jQuery.nodeName( event.target,"a" );
- }
- },