美文网首页
JS URL()和URLSearchParams() API接口

JS URL()和URLSearchParams() API接口

作者: keknei | 来源:发表于2021-10-08 17:44 被阅读0次

    以前获取url上面问号"?"后面的参数时候,需要自己写方法获取,现在有现成的API了。例如获取url:http://localhost/index?a=11&b=tony#1212参数a和b的value

    1. new URL(url)
      new URL(window.location).searchParams.get("a");//11
      //或者
      new URL(window.location.href).searchParams.get("a");//11
      
    2. new URLSearchParams(params)
      //window.location.search 是?a=11&b=tony
      console.log(new URLSearchParams(window.location.search).get("b"));//tony
      

    new URL(url)生成的对象

    console.log(new URL(window.location.href));
    
    {
        hash: "#1212",
        host: "localhost",
        hostname: "localhost",
        href: "http://localhost/index?a=11&b=tony#1212",
        origin: "http://localhost",
        password: "",
        pathname: "/index",
        port: "",
        protocol: "http:",
        search: "?a=11&b=tony",
        searchParams: URLSearchParams {},
        username: ""
    }
    

    大部分树形和window.location上的属性一样,我们这里重点说一下searchParams属性,searchParams属性值和new URLSearchParams(window.location.search)属性值是一样的,里面有append、delete、entries、forEach、get、getAll、has、set、sort、toString、values、keys方法,我们获取就用get方法

    URL的静态方法

    1. URL.createObjectURL(object)
      可以把File,Blob或者MediaSource对象变成一个一个唯一的blob URL。其中参数object可以是File,Blob或者MediaSource对象。
    2. URL.revokeObjectURL(objectURL)
      撤消之前使用URL.createObjectURL()创建的URL对象。其中参数objectURL表示之前使用URL.createObjectURL()创建的URL返回值。
    const url=URL.createObjectURL(file)
    img.src=url;
    img.onload = function () {
      // 图片用完后记得释放内存
      URL.revokeObjectURL(url);
    };
    

    相关文章

      网友评论

          本文标题:JS URL()和URLSearchParams() API接口

          本文链接:https://www.haomeiwen.com/subject/ttxcnltx.html