JS decodeURIComponent在Firefix中返回空字符串(最新)

时间:2016-08-20 01:51:33

标签: javascript decodeuricomponent

从StackOverflow获得以下代码。它应该解析URL中的变量,但是当我在for循环中调试sURLVariables的值时,它的值总是为空。有什么想法吗?

var getUrlParameter = function getUrlParameter(sParam) {
  var sPageURL = decodeURIComponent(window.location.search.substring(1)), 
      sURLVariables = sPageURL.split('&'), sParameterName, i;

  for (i = 0; i < sURLVariables.length; i++) {
    sParameterName = sURLVariables[i].split('=');

    if (sParameterName[0] === sParam) {
      return sParameterName[1] === undefined ? true : sParameterName[1];
    }
  }
};

2 个答案:

答案 0 :(得分:1)

您正在使用的代码会查找&#34;搜索&#34; URL的一部分(查询字符串),但您使用的页面没有任何查询字符串。您网页上的网址类似于http://www.atomz.host-ed.me/#?l=en。哈希值(#)之后的所有内容都是URL 片段的一部分。

而不是window.location.search.substring(1),请使用window.location.hash.substring(2)

(或者删除网址片段开头的问号并使用window.location.hash.substring(1)。)

答案 1 :(得分:0)

尝试使用window.location.hrefdocument.URL获取当前页面的完整网址。更多关于他们:

  1. https://developer.mozilla.org/en-US/docs/Web/API/Document/location
  2. https://developer.mozilla.org/en-US/docs/Web/API/Document/URL