以编程方式点击<a>-tag not working in Firefox

时间:2015-08-26 11:52:01

标签: javascript jquery firefox click

I have a problem with the click()-function from jquery. I create a <a>-element with document.createElement('a') and want call the click()-function about this element. About this element, I want to create an Excel-file and save this at the desktop.

My code:

$('body').on('click', '#test', function(event) {
    var link = document.createElement('a');
    link.download = 'test.xls';
    link.href = 'data:application/vnd.ms-excel;utf-8,test';
    link.click();
});

This function work under chrome, but not under Firefox.

Working example

有谁知道为什么不起作用?

5 个答案:

答案 0 :(得分:91)

在Firefox中,您可以将创建的元素显式添加到DOM中,它将起作用:

$('body').on('click', '#test', function(event) {
    var link = document.createElement('a');
    // Add the element to the DOM
    link.setAttribute("type", "hidden"); // make it hidden if needed
    link.download = 'test.xls';
    link.href = 'data:application/vnd.ms-excel;utf-8,test';
    document.body.appendChild(link);
    link.click();
    link.remove();
});

Fiddle

答案 1 :(得分:65)

即使在FireFox中,您也不必将元素添加到DOM中。 使用以下代码替换.click()方法:

link.dispatchEvent(new MouseEvent(`click`, {bubbles: true, cancelable: true, view: window}));

&#13;
&#13;
$('button').on('click', function(event) {
    var link = document.createElement('a');
    link.download = 'test.xls';
    link.href = 'data:application/vnd.ms-excel;utf-8,test';
    link.dispatchEvent(new MouseEvent('click', {bubbles: true, cancelable: true, view: window}));
});
&#13;
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button>Download</button>
&#13;
&#13;
&#13;

答案 2 :(得分:6)

在触发点击之前将元素添加到DOM:

document.body.appendChild(link);
link.click();
document.body.removeChild(link);

这对所有主流浏览器都有效

答案 3 :(得分:1)

您可以使用jquery创建元素。它适用于两种浏览器

$(document).on('click', '#test', function (event) {
    var link = $("<a/>", {
        "download": "test.xls",
        "href": "data:application/vnd.ms-excel;utf-8,test"
    });
    $("#test").append(link);
    link.get(0).click();
});

Fiddle

答案 4 :(得分:0)

  var fileUrl=document.createElement('a');
      fileUrl.href=response.request.responseURL;
      document.body.appendChild(fileUrl);
      fileUrl.click();

添加文档正文,多数民众赞成在工作