In Jörn's version of the code, you wouldn't call $.query() at all. Instead, $.query would be the resulting object that you would then use directly. Note that jQuery and $ are references to the same object, so jQuery.query and $.query are the same thing.
I'm not sure I like this idea since it means the query parsing would be done whether you need it or not. But maybe it doesn't take enough time to worry about. If it does run all the time, it would be worth optimizing the code by using a conventional for loop instead of jQuery.each and combining the repeated "split" calls. I'd also remove the code that does the float conversion and ignores empty values. Consider this URL: http://www.example.com/test?special=&zip=00125 I may want to know about that "special" parameter, and I probably don't want the Zip code turned into the number 125. Here's how I would code it... For the "jQuery.query is an object" version: (function() { var r = jQuery.query = {}; var params = location.search.replace(/^\?/,'').split('&'); for( var i = params.length-1; i >= 0; i-- ) { var p = params[i].split('='), key = p[0]; if( key ) r[key] = p[1]; } })(); For the "jQuery.query is a function": jQuery.query = function() { var r = {}; var params = location.search.replace(/^\?/,'').split('&'); for( var i = params.length-1; i >= 0; i-- ) { var p = params[i].split('='), key = p[0]; if( key ) r[key] = p[1]; } return r; }; All untested, of course. :-) -Mike > From: Stephen Woodbridge > I seem to be missing something (so much to learn!). Your note > creates an anonymous function that assigns its result to > jQuery.query, but where does the function get attached and > how does it get invoked, like in Luke's example. > Jörn Zaefferer wrote: > > In that case, you should just assign the result to jQuery.query, eg: > > (function() { > > > > jQuery.query = r = {}; > > var q = location.search; > > q = q.replace(/^\?/,''); // remove the leading ? > > q = q.replace(/\&$/,''); // remove the trailing & > > jQuery.each(q.split('&'), function(){ > > var key = this.split('=')[0]; > > var val = this.split('=')[1]; > > // convert floats > > if(/^[0-9.]+$/.test(val)) > > val = parseFloat(val); > > // ingnore empty values > > if(val) > > r[key] = val; > > }); > > > > })(); > > > > Considering that location.search does not change. I hope I'm not > > confusing something. _______________________________________________ jQuery mailing list [email protected] http://jquery.com/discuss/
