简体   繁体   English

函数内部未定义URLSearchParams错误

[英]URLSearchParams not defined error Inside A Function

This is very odd, using DW CC 2018 (in case that is where the problem is), when i use URLSearchParams inside a script tag in my HTML page, it does not get flagged as an "error". 这很奇怪,使用DW CC 2018(如果问题出在哪里),当我在HTML页面的脚本标签内使用URLSearchParams时,它不会被标记为“错误”。

I put URLSearchParams in my external JS file, inside a function, it gets flagged as "not defined". 我将URLSearchParams放在函数中的外部JS文件中,将其标记为“未定义”。 DW flags it as an error, but it still works, so must be more of a "warning" than an error. DW将其标记为错误,但是它仍然可以工作,因此,它必须比错误更像是“警告”。 This has me a bit concerned even if it is a warning, that it could break when going live. 即使发出警告,这也让我有些担心,因为它可能会在上线时发生故障。

Should I worry, or is it just once of those things to just ignore? 我应该担心,还是只是其中的一件事情而忽略?

Dreamweaver probably uses an outdated list of "expected globals" in its indexer that isn't updated to include the URLSearchParams API , since it's relatively recent. Dreamweaver可能在其索引器中使用了过时的“预期全局变量”列表,由于它是相对较新的,因此未更新为包括URLSearchParams API

If you're not concerned with backwards compatibility *cough* IE *cough* , just add this somewhere in the offending file to get Dreamweaver to shut up: 如果您不关心向后兼容性* cough * IE * cough * ,只需将其添加到有问题的文件中以使Dreamweaver关闭:

const URLSearchParams = window.URLSearchParams;

If Dreamweaver doesn't support ES6 syntax (I've never used it), then you must add this somewhere that's not at the top level: 如果Dreamweaver不支持ES6语法(我从未使用过),则必须将其添加到不在顶层的位置:

(function () {
  // must be in a closure
  var URLSearchParams = window.URLSearchParams;

  ...
})();

The reason why is because top-level var overwrites the global namespace in some browsers. 原因是因为顶级var在某些浏览器中会覆盖全局名称空间。

you can write custom URLSearchParams class 您可以编写自定义URLSearchParams类

class UrlSearchParams {
  constructor(query) {
    this.query = query;
  }
  getSearchObject = () => {
    const { query } = this;
    return query
    ? (/^[?#]/.test(query) ? query.slice(1) : query)
      .split("&")
      .reduce((params, param) => {
        let [key, value] = param.split("=");
        params[key] = value
          ? decodeURIComponent(value.replace(/\+/g, " "))
          : "";
        return params;
      }, {})
  : {};
  };
  getAll = () => {
    const searchParams = this.getSearchObject();
    return searchParams;
  }
  get = param => {
    const searchParams = this.getSearchObject();
    return searchParams[param];
  };
  setUrl = (param, value) => {
    const searchParams = this.getSearchObject();
    searchParams[param] = value;
    return Object.keys(searchParams)
    .map(key => key + "=" + searchParams[key])
    .join("&");
  };
}

export default UrlSearchParams;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM