javascript 使用 JQuery 单击“下载”链接不会下载文件

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/25507314/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-28 04:36:22  来源:igfitidea点击:

click on "download" link using JQuery doesn't download file

javascriptjqueryhtml

提问by Alexander

I have a link with href and download attributes:

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

  <a id="lnk" href="data:text/csv;charset=utf-8,1%2C2%2C3" download="my_file.csv">click to download</a>

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

当我点击它(例如在 Chrome 中)时,会按预期下载一个 csv 文件“my_file.csv”。

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

现在我希望能够以编程方式导致此操作。因此,我正在尝试使用 JQuery:

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

or

或者

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

but the file is not downloaded.

但文件没有下载。

Here is the code: http://jsbin.com/yereg/3/edit

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

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

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

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

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.

但这样我无法设置文件名(链接按download="my_file.csv"属性进行)。如果有设置文件名的方法,则此解决方案很好。

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

备注:就我而言,应该支持 Chrome 和 Firefox。我不关心其余的浏览器。

回答by UweB

from the jquery documentation:

来自 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.

点击事件仅在这一系列事件之后触发:

当指针在元素内时,鼠标按钮被按下。当指针在元素内时释放鼠标按钮。

You could resort to calling the JavaScript native event, through

您可以通过调用 JavaScript 本机事件

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

Or safer:

或者更安全:

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


EDIT:

编辑:

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.jsin the latest jQuery version (2.1.x), especially the comment:

出于好奇,我查看了 jQuery 源代码是如何完成的。事实证明,它们是故意阻止浏览器在链接上的本机单击事件,请参阅events.js最新 jQuery 版本 (2.1.x) 中的以下摘录,尤其是注释:

click: {
    [...]

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

回答by karan3112

Try using $('#lnk')[0].click()

尝试使用 $('#lnk')[0].click()

JS :

JS:

$('#btn1').on('click', function(){
  $('#lnk')[0].click();
});