点击“下载"使用JQuery的链接不会下载文件 [英] click on "download" link using JQuery doesn't download file

查看:86
本文介绍了点击“下载"使用JQuery的链接不会下载文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个带有href和下载属性的链接:

I have a link with href and download attributes:

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

When I click on it (in Chrome for example) a csv file "my_file.csv" is downloaded as supposed.

现在,我希望能够以编程方式执行此操作.因此,我尝试使用JQuery:

Now I want to be able to cause this action programmatically. So using JQuery I am trying to do:

$('#lnk').click();

$('#lnk').trigger("click");

但文件未下载.

这是代码: http://jsbin.com/yereg/3/edit

我可以从链接中复制链接地址,然后只使用window.open:

I could copy the link address from the link and then just use window.open:

window.open('data:text/csv;charset=utf-8,1%2C2%2C3');

但是这种方式我无法设置文件名(链接通过 download ="my_file.csv" 属性完成).如果可以设置文件名,则此解决方案很好.

but this way I can't set the file name (link does by download="my_file.csv" attribute). This solution is fine if there is a way to set the file name.

备注:在我的情况下,应支持Chrome和Firefox.我不在乎其他浏览器.

Remark: in my case Chrome and Firefox should be supported. I don't care about the rest of the browsers.

推荐答案

:

只有在以下一系列确切的事件之后才触发click事件:

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本机事件:

You could resort to calling the JavaScript native event, through

$('#lnk').get(0).click();

或更安全:

var lnk = document.getElementById('lnk');
if (lnk) {
    lnk.click();
}


出于好奇,我看了一下jQuery来源是如何完成的.事实证明,它们阻止了浏览器的本地单击事件,特别是故意使链接发生点击,请参见最新jQuery版本(2.1.x)中 events.js 的以下摘录,尤其是注释:

Out of curiosity, I had a look at the jQuery sources how it's done. It turns out that they prevent the native click event of the browser on links in particular on purpose, see the following excerpt from the events.js in the latest jQuery version (2.1.x), especially the comment:

click: {
    [...]

    // For cross-browser consistency, don't fire native .click() on links
    _default: function( event ) {
        return jQuery.nodeName( event.target, "a" );
    }
},

这篇关于点击“下载"使用JQuery的链接不会下载文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆