当前位置: 动力学知识库 > 问答 > 编程问答 >

javascript - Programatical click on <a>-tag not working in Firefox

问题描述:

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 a 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: http://jsfiddle.net/0hnuw6b4/1/

Does anyone have any idea why that does not work?

网友答案:

In Firefox, you can explicitly add the created element to the DOM and it will work:

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

Fiddle

网友答案:

You can use jquery for creating the element. It will work on both the browsers

$(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

分享给朋友:
您可能感兴趣的文章:
随机阅读: