Whi*_*ite 49 javascript firefox jquery click
我有click()来自jquery 的-function 的问题.我创建了一个<a>-element,document.createElement('a')并希望调用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();
});
Run Code Online (Sandbox Code Playgroud)
此功能在chrome下运行,但不在Firefox下运行.
有谁知道为什么那不起作用?
lur*_*ker 103
在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();
});
Run Code Online (Sandbox Code Playgroud)
Den*_*ler 90
您不必将元素添加到DOM,即使在FireFox中也是如此.用以下代码替换.click()方法:
link.dispatchEvent(new MouseEvent(`click`, {bubbles: true, cancelable: true, view: window}));
Run Code Online (Sandbox Code Playgroud)
小智 7
在触发点击之前将元素添加到DOM:
document.body.appendChild(link);
link.click();
document.body.removeChild(link);
Run Code Online (Sandbox Code Playgroud)
这对所有主要浏览器都有效
您可以使用 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();
});
Run Code Online (Sandbox Code Playgroud)