Given a link like so:
<a href="/users/xxxx?width=640" class="dialogOnClick">Create Account</a>
I have
$('.dialogOnClick').live('click', function() {
// How to get开发者_运维百科 640, given we look for the width param?
console.log( $(this).?????)
});
When a user clicks on a link with the class dialogOnClick, I want to check if there is a width query param and if so, obtain the value. In the case above being 640. Is this possible?
Thanks
The element's search
property will contain the query string.
Then you could either parse it into key & value pairs, or just use a regex for this simple example.
$('.dialogOnClick').live('click', function() {
console.log( this.search.match(/width=(\d+)/)[1] );
});
jsFiddle.
This will fail if there are no matches however. You may want to assign the return of match()
to a variable and test if first to ensure it has required element.
$('.dialogOnClick').live('click', function() {
var href = $(this).attr('href');
var indexOfWidth = href.indexOf('width=');
var value = href.substr(indexOfWidth).split("=")[1];
console.log( value );
});
jsfiddle
If you just want the trailing numeric value, then you can use:
this.href.match(/\d+$/)[0];
However, if you specifically want the width value, you can use:
this.href.match(/width=\d+/)[0].match(/\d+$/)[0]
Or if you want a more robust method to get one parameter of many, then you need to parse the URL:
function getParams(url) {
var paramString = url.split('?')[1];
var paramArray = [];
var params = {};
var p;
if (paramString && paramString.length) {
paramArray = paramString.split('&');
for (var i=0, iLen=paramArray.length; i<iLen; i++) {
p = paramArray[i].split('=');
params[p[0]] = p[1];
}
}
return params;
}
and can do:
getParams(this.href)['width'];
POJS working example:
<a href="/users/xxxx?width=640" class="dialogOnClick"
onclick="alert(this.href.match(/\d+$/)[0]);return false;">Create Account</a>
<a href="/users/xxxx?width=640" class="dialogOnClick"
onclick="alert(getParams(this.href).width);return false;">Create Account 2</a>
You can use jQuery to get the contents of href
:
var href = $(this).attr('href');
And a regular expression to parse that text to determine if there is a width parameter, and to extract the value:
var pattern = /width=([0-9]*)/g;
var match;
while (match = pattern.exec(href))
{
alert(match);
// Do something with the match (["width=640", "640"]) here...
}
Here is a live example.
精彩评论