以编程方式单击 -tag在Firefox中不起作用
我有来自jquery的click()
函数的问题。 我用document.createElement('a')
创建了一个 -element,并且想要调用关于这个元素的
click()
-function。 关于这个元素,我想创建一个Excel文件并将其保存在桌面上。
我的代码:
$('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(); });
此function在chrome下运行,但不在Firefox下运行。
工作实例
有谁知道为什么那不起作用?
在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(); });
小提琴
您不必将元素添加到DOM,即使在FireFox中也是如此。 用以下代码替换.click()方法:
link.dispatchEvent(new MouseEvent(`click`, {bubbles: true, cancelable: true, view: window}));