Jquery / Javascript从窗口位置获取params

时间:2012-03-10 21:26:32

标签: javascript jquery

我的网址是:

http://localhost:3000/?sort=rating

参数sort是动态的,我想将其添加到另一个网址。

在我的javascript中我有:

window.location.pathname + '.js?page=' + currentPage

如何在最后添加sort参数?

示例:

window.location.pathname + '.js?page=' + currentPage + &sortparam

在这种情况下,它将是:

window.location.pathname + '.js?page=' + currentPage + '&sort=rating'

3 个答案:

答案 0 :(得分:2)

以下是您要找的内容:

How can I get query string values in JavaScript?

在你的情况下:

function getParameterByName(name)
{
  name = name.replace(/[\[]/, "\\\[").replace(/[\]]/, "\\\]");
  var regexS = "[\\?&]" + name + "=([^&#]*)";
  var regex = new RegExp(regexS);
  var results = regex.exec(window.location.search);
  if(results == null)
    return "";
  else
    return decodeURIComponent(results[1].replace(/\+/g, " "));
}

var sortparam = getParameterByName("sort");
window.location.pathname + '.js?page=' + currentPage + '&sort='+sortparam

答案 1 :(得分:1)

这是另外一个,稍微更通用的包装器:

function getParams() {

  var params = window.location.search.substring(1).split('& '),
    i = 0,
    pair = null,
    result = {};

  while (pair = params[i++]) {
    pair = pair.split('=');
    result[pair[0]] = decodeURIComponent(pair[1]);
  }

  return result;
}

alert(getParams().page);

答案 2 :(得分:0)

window.location.pathname + '.js?page=' + currentPage +
    "&" + location.search.match(/(sort=.*?)&|$/)[1]