有人知道编写jQuery扩展来处理查询字符串参数的好方法吗?我基本上想要扩展jQuery Magic ($)函数,这样我就可以执行如下操作:

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

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

我在jQuery和Javascript中看到了很多可以做到这一点的函数,但我实际上想要扩展jQuery,使其工作起来与上面显示的完全一样.我不是在寻找jQuery插件,我是在寻找jQuery方法的扩展.

推荐答案

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

//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"

UPDATE : IE is not supported

an answer below而不是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相关问答推荐

如何在光滑的轮播上添加进度条

点击和touch 事件之间的jQuery冲突解决方法

为什么函数没有进入

formData.append 来自不同输入文件的两个文件

为什么 .join() 不能与函数参数一起使用?

jQuery函数从数组中获取所有唯一元素?

递归循环遍历对象(树)

jQuery:获取所选单选按钮的父 tr

在jQuery中获取所有选定复选框值的最佳方法

数据表警告(表 id = 'example'):无法重新初始化数据表

如何计算具有相同类的元素数量?

如何在 Slick 轮播项目之间添加空格

调整浏览器大小时调整jqGrid的大小?

jQuery中追加的相反

使用带有 HTML 表格的 jQuery UI 可排序

如何使用 jQuery 格式化电话号码

在事件中使用 jQuery 获取被点击的元素?

jQuery.active 函数

如何在没有鼠标事件的情况下在 jQuery 中获取鼠标位置?

Twitter Bootstrap - 选项卡 - URL 不变