码迷,mamicode.com
首页 > 其他好文 > 详细

模拟点击及下载(a标签有关)

时间:2021-05-24 05:33:57      阅读:0      评论:0      收藏:0      [点我收藏+]

标签:lin   nload   模拟   name   blob   down   let   a标签   事件   

模拟点击事件
function triggerclick(ele){
if(ele instanceof $){
ele = ele[0]
}
var clickEvent = document.createEvent("MouseEvents");
clickEvent.initEvent("click", true, true);
ele.dispatchEvent(clickEvent);
}

 

下载文件,支持重命名
 
function downloadFile(url, name = "file.json") {
let a = document.createElement("a")
a.setAttribute("href", url)
a.setAttribute("target", "_blank")
a.setAttribute("download", name)
let clickEvent = document.createEvent("MouseEvents");
clickEvent.initEvent("click", true, true);
a.dispatchEvent(clickEvent);
}

 

数据保存为json格式到本地
function downloadFileByJSON(json) {
var blob = new Blob([JSON.stringify(json)], { type: "text/plain;charset=utf-8" })
var url = URL.createObjectURL(blob);
downloadFile(url)
}

 

数据保存为text文本到本地
function downloadFileByText(text, name) {
var blob = new Blob([text], { type: "text/plain;charset=utf-8" })
var url = URL.createObjectURL(blob);
downloadFile(url, name)
}

 

模拟点击及下载(a标签有关)

标签:lin   nload   模拟   name   blob   down   let   a标签   事件   

原文地址:https://www.cnblogs.com/zmdblog/p/14755503.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!