Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
302 views
in Technique[技术] by (71.8m points)

javascript - Programmatical 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 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

Does anyone have any idea why that does not work?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...