简体   繁体   English

如果本地存储变量为空,如何什么都不做

[英]How to do nothing if local storage variable is empty

I am using the script below to append utm parameters to the end of a page's URL.我正在使用下面的脚本将 utm 参数附加到页面 URL 的末尾。 However, sometimes there will be no parameters, thus meaning nothing in the local storage variable.但是,有时会没有参数,因此在本地存储变量中没有任何意义。

The problem : when there is nothing in local storage, it currently appends ?null to the end of the URL.问题:当本地存储中没有任何内容时,它当前将?null附加到 URL 的末尾。

<script type="text/javascript">
  // Get parameters from local storage
  var parameters = localStorage.getItem("query");

  if(window.location.href.indexOf('?' + parameters) == -1){

    // Identify next URL
    const nextURL = window.location.href + '?' + parameters;

    // Replace current entry in browser history
    window.history.replaceState('', '', nextURL);
  }
</script>

You can check if the local storage variable is empty.您可以检查本地存储变量是否为空。

Using your example, you could change it to this:使用您的示例,您可以将其更改为:

<script type="text/javascript">
  // Get parameters from local storage
  var parameters = localStorage.getItem("query");

  if (!parameters) return; // <--- you could add this line.

  if(parameters && // <---- or add this condition
      window.location.href.indexOf('?' + parameters) == -1){

    // Identify next URL
    const nextURL = window.location.href + '?' + parameters;

    // Replace current entry in browser history
    window.history.replaceState('', '', nextURL);
  }
</script>

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

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