使用jQuery从URL获取查询字符串

编程入门 行业动态 更新时间:2024-10-21 20:41:39
本文介绍了使用jQuery从URL获取查询字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我有以下网址:

www.mysite.co.uk/?location=mylocation1

我需要从URL中获取location的值到一个变量中,然后在jQuery代码中使用它:

I need to get the value of location from the URL into a variable and then use it in jQuery code:

var thequerystring = "getthequerystringhere" $('html,body').animate({scrollTop: $("div#" + thequerystring).offset().top}, 500);

如何使用JavaScript或jQuery来获取该值?

How can I grab that value using JavaScript or jQuery?

推荐答案

来自: jquery-howto.blogspot/2009/09/get-url-parameters-values-with-jquery.html

这就是您所需要的:)

以下代码将返回一个包含URL参数的JavaScript对象:

The following code will return a JavaScript Object containing the URL parameters:

// 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; }

例如,如果您具有URL:

For example, if you have the URL:

www.example/?me=myValue&name2=SomeOtherValue

此代码将返回:

{ "me" : "myValue", "name2" : "SomeOtherValue" }

您可以这样做:

var me = getUrlVars()["me"]; var name2 = getUrlVars()["name2"];

更多推荐

使用jQuery从URL获取查询字符串

本文发布于:2023-11-17 12:05:45,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1609946.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:字符串   jQuery   URL

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!