JQuery 如何从href 标签中提取值?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/872217/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 09:58:54  来源:igfitidea点击:

JQuery How to extract value from href tag?

jquery

提问by Malcolm

I am new to JQuery.

我是 JQuery 的新手。

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

如果我有以下标签。从 href 中提取“页面”值的最佳 JQuery 方法是什么?

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

Malcolm

马尔科姆

回答by Matchu

The first thing that comes to my mind is a one-liner regex:

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

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

回答by Kenny Eliasson

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

我不知道你是否要使用它进行分页并将文本放在<a>-tag 中,但如果你应该这样做,你也可以这样做

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

回答by Peter ?rneholm

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

然后看看这个插件:http: //plugins.jquery.com/project/query-object

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

它将帮助您处理您想做的各种查询字符串。

/Peter F

/彼得F

回答by great_llama

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

这是一种通过将查询字符串转换为 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... =)

我会像其他人建议的那样去图书馆...... =)

回答by Iain Holder

Use this jQuery extensionby James Padoley

使用James Padoley 的这个 jQuery扩展

回答by joaquim machado

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