使用 jQuery/Javascript (querystring) 获取查询字符串参数 url 值 [英] Get query string parameters url values with jQuery / Javascript (querystring)

查看:35
本文介绍了使用 jQuery/Javascript (querystring) 获取查询字符串参数 url 值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有谁知道编写 jQuery 扩展来处理查询字符串参数的好方法吗?我基本上想扩展 jQuery 魔法 ($) 函数,这样我就可以做这样的事情:

Anyone know of a good way to write a jQuery extension to handle query string parameters? I basically want to extend the jQuery magic ($) function so I can do something like this:

$('?search').val(); 

这会给我以下 URL 中的值test":http://www.example.com/index.php?search=test.

Which would give me the value "test" in the following URL: http://www.example.com/index.php?search=test.

我已经看到很多可以在 jQuery 和 Javascript 中执行此操作的函数,但实际上我想扩展 jQuery 以使其完全如上所示工作.我不是在寻找 jQuery 插件,而是在寻找 jQuery 方法的扩展.

I've seen a lot of functions that can do this in jQuery and Javascript, but I actually want to extend jQuery to work exactly as it is shown above. I'm not looking for a jQuery plugin, I'm looking for an extension to the jQuery method.

推荐答案

经过多年丑陋的字符串解析,有一个更好的方法:URLSearchParams 让我们来看看如何使用这个新的 API从位置获取值!

After years of ugly string parsing, there's a better way: URLSearchParams Let's have a look at how we can use this new API to get values from the location!

//Assuming URL has "?post=1234&action=edit"

var urlParams = new URLSearchParams(window.location.search);
console.log(urlParams.has('post')); // true
console.log(urlParams.get('action')); // "edit"
console.log(urlParams.getAll('action')); // ["edit"]
console.log(urlParams.toString()); // "?post=1234&action=edit"
console.log(urlParams.append('active', '1')); // "?

post=1234&action=edit&active=1"

更新:不支持 IE

使用下面的答案中的此函数,而不是URLSearchParams

$.urlParam = function (name) {
    var results = new RegExp('[?&]' + name + '=([^&#]*)')
                      .exec(window.location.search);

    return (results !== null) ? results[1] || 0 : false;
}

console.log($.urlParam('action')); //edit

这篇关于使用 jQuery/Javascript (querystring) 获取查询字符串参数 url 值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆