Possivel duplicata: Como posso obter os valores das strings de consulta?
Eu tenho o seguinte URL:
http://www.mysite.co.uk/?location=mylocation1
O que eu preciso é obter o valor de location
da URL para uma variável e depois utilizá-la em um código jQuery:
var thequerystring = "getthequerystringhere"
$('html,body').animate({scrollTop: $("div#" + thequerystring).offset().top}, 500);
Alguém sabe como agarrar esse valor usando JavaScript ou jQuery?
De: http://jquery-howto.blogspot.com/2009/09/get-url-parameters-values-with-jquery.html
Isto é o que você precisa :)
O seguinte código irá retornar um objeto JavaScript contendo os parâmetros URL:
// Read a page's GET URL variables and return them as an associative array.
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;
}
Por exemplo, se você tiver o URL:
http://www.example.com/?me=myValue&name2=SomeOtherValue
Este código vai voltar:
{
"me" : "myValue",
"name2" : "SomeOtherValue"
}
e você pode fazer:
var me = getUrlVars()["me"];
var name2 = getUrlVars()["name2"];
Uma maneira fácil de fazer isto com jQuery e straight JS, basta ver o seu console em Chrome ou Firefox para ver a saída...
var queries = {};
$.each(document.location.search.substr(1).split('&'),function(c,q){
var i = q.split('=');
queries[i[0].toString()] = i[1].toString();
});
console.log(queries);
Dê uma olhada nesta resposta de stackoverflow.
function getParameterByName(name, url) {
if (!url) url = window.location.href;
name = name.replace(/[\[\]]/g, "\\$&");
var regex = new RegExp("[?&]" + name + "(=([^&#]*)|&|#|$)"),
results = regex.exec(url);
if (!results) return null;
if (!results[2]) return '';
return decodeURIComponent(results[2].replace(/\+/g, " "));
}
Você pode usar o método para animar:
isto é:
var thequerystring = getParameterByName("location");
$('html,body').animate({scrollTop: $("div#" + thequerystring).offset().top}, 500);