简体   繁体   中英

JQuery How to extract value from href tag?

I am new to JQuery.

If I have the following tag. What is the best JQuery method to extract the value for "page" from the href.

<a href="Search/Advanced?page=2">2</a>

Malcolm

我想到的第一件事就是单行正则表达式:

var pageNum = $("#specificLink").attr("href").match(/page=([0-9]+)/)[1];

I see two options here

var link = $('a').attr('href');
var equalPosition = link.indexOf('='); //Get the position of '='
var number = link.substring(equalPosition + 1); //Split the string and get the number.

I dont know if you're gonna use it for paging and have the text in the <a> -tag as you have it, but if you should you can also do

var number = $('a').text();

First of all you need to extract the path with something like this:

$("a#myLink").attr("href");

Then take a look at this plugin: http://plugins.jquery.com/project/query-object

It will help you handle all kinds of querystring things you want to do.

/Peter F

Here's a method that works by transforming the querystring into JSON...

var link = $('a').attr('href');

if (link.indexOf("?") != -1) {
    var query = link.split("?")[1];

    eval("query = {" + query.replace(/&/ig, "\",").replace(/=/ig, ":\"") + "\"};");

    if (query.page)
        alert(unescape(query.page));
    else
        alert('No page parameter');

} else {
    alert('No querystring');
}

I'd go with a library like the others suggest though... =)

使用James Padoley的这个jQuery 扩展

if ($('a').on('Clicked').text().search('1') == -1)
{
    //Page == 1
}
else
{
    //Page != 1
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM