在jquery中通过URL传递1或2个查询字符串的问题

时间:2017-02-26 19:40:15

标签: javascript jquery

如果我选择在网址上添加1或2个变量,我正在尝试向网页添加一些自定义内容。问题是我的函数只在两个字符串都通过时才有效,而不是我只选择使用1.我想要的选项。传递的2个字符串是'rescompany'和'locale'

re:index.html?locale=someplace&rescompany=Google

$(document).ready(function() {
      function getUrlVars() {
        var vars = [],
          hash;
        var hashes = window.location.href.slice(window.location.href.indexOf('?') + 1).split('&');
        for (var i = 0; i < hashes.length; i++) {
          hash = hashes[i].split('=');
          vars.push(hash[0]);
          vars[hash[0]] = hash[1];
        }
        return vars;
      }

      if (document.location.search.length) {
        var rescompany = getUrlVars()["rescompany"];
        var locale = getUrlVars()["locale"];

        if ((rescompany).length > 0) {
          $(".addtores").css('visibility', 'visible');
          $(".resname").append(decodeURIComponent(rescompany));
        }
        if ((locale).length > 0) {
          $(".introduction strong span").css('display', 'inline-block');
        }
      }

1 个答案:

答案 0 :(得分:0)

如果我运行您的代码,我收到以下错误消息:TypeError: rescompany is undefined(检查浏览器中的错误消息)

这意味着你的if test (rescompany).length > 0是错误的。这应该替换为rescompany !== undefined

所以,你的代码应该是这样的:

$(document).ready(function() {
  function getUrlVars() {
    var vars = [],
      hash;
    var hashes = window.location.href.slice(window.location.href.indexOf('?') + 1).split('&');
    for (var i = 0; i < hashes.length; i++) {
      hash = hashes[i].split('=');
      vars.push(hash[0]);
      vars[hash[0]] = hash[1];
    }
    return vars;
  }

  if (document.location.search.length) {
    var vars = getUrlVars();
    var rescompany = vars["rescompany"];
    var locale = vars["locale"];

    if (rescompany !== undefined) {
      $(".addtores").css('visibility', 'visible');
      $(".resname").append(decodeURIComponent(rescompany));
    }
    if (locale !== undefined) {
      $(".introduction strong span").css('display', 'inline-block');
    }
  }
});