开发者

Using jQuery, how can I grab value from href?

开发者 https://www.devze.com 2023-01-20 04:00 出处:网络
I have a bunch of links on my page, in the format: <a href=\"/q/10/Title\">Title</a> How can I grab the \"10\" from this link and use it as a variab开发者_StackOverflow社区le?

I have a bunch of links on my page, in the format:

<a href="/q/10/Title">Title</a>

How can I grab the "10" from this link and use it as a variab开发者_StackOverflow社区le?

Thanks.


Use $('a').attr('href') to get the path, and then you can use String#split to break it up.

https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/String/split


You can search for 1 or more digits ([\d]+) with a regex in the href attribute of the a tag:

​var theNumber = /[\d]+/.exec( $("a").attr("href") );​​​​​​​​​​​​​

Try it out with this jsFiddle

The above will find the first number in the href of the first a tag. You can of course use other jQuery selectors.

0

精彩评论

暂无评论...
验证码 换一张
取 消