目 录CONTENT

文章目录

Javascript function

J
J
2024-11-13 / 0 评论 / 0 点赞 / 259 阅读 / 5804 字 / 正在检测是否收录...
温馨提示:
本文最后更新于 2025-07-10,若内容或图片失效,请留言反馈。部分素材来自网络,若不小心影响到您的利益,请联系我们删除。

下载convas中的图片 👍

var convas = document.getElementById("canvas");

var dataURL = convas.toDataURL();

var link = document.createElement('a');

link.href=dataURL;

link.download='image.png';

document.body.appendChild(link);

link.click();

下载svg中的图片 👍

svg无法当成图片打开,可以使用工具转换成你想要的图片格式

var svg =document.getElementById("aaa")

var svgData=new XMLSerializer().serializeToString(svg);

var blob=new Blob([svgData],{type:"image/svg+xml;charset=utf-8"});

var url=URL.createObjectURL(blob);

var a=document.createElement("a");

a.href=url;

a.download="image.svg";

a.click();

写入cookie

//name=>key value=>cookie值 daysToExpire=>失效时间 传空则默认浏览器关闭就失效
function setCookie(name, value, daysToExpire) {
    var expirationDate = '';
    if (daysToExpire) {
        var expirationTime = new Date();
        expirationTime.setTime(expirationTime.getTime() + (daysToExpire * 24 * 60 * 60 * 1000));
        expirationDate = "; expires=" + expirationTime.toUTCString();
    }

    document.cookie = name + "=" + value + expirationDate + "; path=/";
}

读取cookie

//读取cookie
function getCookie(name) {
    var cookieName = name + "=";
    var cookiesArray = document.cookie.split(';');
    for (var i = 0; i < cookiesArray.length; i++) {
        var cookie = cookiesArray[i].trim();
        if (cookie.indexOf(cookieName) === 0) {
            return cookie.substring(cookieName.length, cookie.length);
        }
    }
    return null;
}

转换成字符串

//举例:
//var boolValue = true;
//console.log(String(boolValue) === "true");
function boolToString(val){
   return String(val);
}

获取checkbox是否选中

//ele => $(".chkbox");
//获取checkbox选中属性
function getChkboxIsSelect(ele){
  ele.prop("checked");// true / false
}

使用父级页面的function时,判断funciton是否存在

//父级方法存在,则调用
function fatherfunctionIsExist(){
  //funcName 为你要使用的父级function
  if (window.parent && typeof window.parent.funcName === 'function') {
      window.parent.funcName();
  }
}

获取url中的参数

    //返回值是object {a:"我是a",b:"我是b"}
    function getUrlParameters() {
        var urlParams = {};
        var match,
            regex = /([^&=]+)=([^&]*)/g;
        var searchString = window.location.search.substring(1);
        while ((match = regex.exec(searchString))) {
            var key = decodeURIComponent(match[1]);
            var value = decodeURIComponent(match[2]);
            urlParams[key] = value;
        }
        return urlParams;
    }

使用fetch请求c#后台下载文件

    ///使用fetch post请求c# 后台下载文件 包含错误信息捕获(可自定义,也可以是程序异常)
    function postJsonAndDownload() {
        var body="你的实体对象";
        fetch("你的url", {
            method: "POST",
            headers: {
                "Content-Type": "application/json"
            },
            body: JSON.stringify(body)
        })
            .then(async response => {
                //当后台返回Content类型的时候,与File的content-type不一致,所以这里用来捕获后台的报错信息
                const contentType = response.headers.get("Content-Type") || "";

                // 检查是否成功响应文件
                if (!response.ok) {
                    alert("服务器响应失败");
                    return;
                }

                if (contentType.includes("application/json") || contentType.includes("text/plain")) {
                    const errorText = await response.text();//要想得到后台的提示信息,这里必须要使用 async + await,不然这里获取到的会是一个对象
                    throw new Error(errorText); // 👈 这里抛出后续 catch 接收
                }
                // 获取文件名(可选)
                const disposition = response.headers.get("Content-Disposition");
                let fileName = "report.pdf";
                if (disposition && disposition.indexOf("filename=") !== -1) {
                    fileName = decodeURIComponent(disposition.split("filename=")[1].replace(/['"]/g, ""));
                }

                return response.blob().then(blob => ({ blob, fileName }));
            })
            .then(({ blob, fileName }) => {
                // 创建 Blob URL 并下载
                const blobUrl = window.URL.createObjectURL(blob);
                const link = document.createElement("a");
                link.href = blobUrl;
                link.download = fileName;
                document.body.appendChild(link);
                link.click();
                link.remove();
                window.URL.revokeObjectURL(blobUrl);
            })
            .catch(err => {
                alert("下载失败:" + err.message);
            })
            .finally(() => {
                //常用的一些方法,比如遮罩层 ...
            })
    }

0

评论区