Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
346 views
in Technique[技术] by (71.8m points)

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

Anyone know of a good way to write a jQuery extension to handle query string parameters?(有人知道编写jQuery扩展来处理查询字符串参数的好方法吗?)

I basically want to extend the jQuery magic ($) function so I can do something like this:(我基本上想扩展jQuery magic ($)函数,所以我可以这样做:) $('?search').val(); Which would give me the value "test" in the following URL: http://www.example.com/index.php?search=test .(这将在以下URL中为我提供值“test”: http://www.example.com/index.php?search=testhttp://www.example.com/index.php?search=test test。) 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.(我已经看到很多函数可以在jQuery和Javascript中执行此操作,但实际上我希望扩展jQuery以完全按照上面所示的方式工作。) I'm not looking for a jQuery plugin, I'm looking for an extension to the jQuery method.(我不是在寻找一个jQuery插件,我正在寻找jQuery方法的扩展。)   ask by TroySteven translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Why extend jQuery?(为什么要扩展jQuery?)

What would be the benefit of extending jQuery vs just having a global function?(扩展jQuery与仅具有全局功能有什么好处?) function qs(key) { key = key.replace(/[*+?^$.[]{}()|\/]/g, "\$&"); // escape RegEx meta chars var match = location.search.match(new RegExp("[?&]"+key+"=([^&]+)(&|$)")); return match && decodeURIComponent(match[1].replace(/+/g, " ")); } http://jsfiddle.net/gilly3/sgxcL/(http://jsfiddle.net/gilly3/sgxcL/) An alternative approach would be to parse the entire query string and store the values in an object for later use.(另一种方法是解析整个查询字符串并将值存储在对象中供以后使用。) This approach doesn't require a regular expression and extends the window.location object (but, could just as easily use a global variable):(这种方法不需要正则表达式并扩展window.location对象(但是,可以很容易地使用全局变量):) location.queryString = {}; location.search.substr(1).split("&").forEach(function (pair) { if (pair === "") return; var parts = pair.split("="); location.queryString[parts[0]] = parts[1] && decodeURIComponent(parts[1].replace(/+/g, " ")); }); http://jsfiddle.net/gilly3/YnCeu/(http://jsfiddle.net/gilly3/YnCeu/) This version also makes use of Array.forEach() , which is unavailable natively in IE7 and IE8.(此版本还使用了Array.forEach() ,它在IE7和IE8 Array.forEach()不可用。) It can be added by using the implementation at MDN , or you can use jQuery's $.each() instead.(它可以通过在MDN上使用实现来添加,或者您可以使用jQuery的$.each()代替。)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...