开发者

Getting all links on a page that match a url string

I'm currently using this code (along with Mootools) to build an array of all anchors in the #subnav div that contain a specific url string:

$('subnav').getElements('a[href*=/'+href+']')

Problem is if I'm looking for work.aspx?subsection=24&project=1 that will match anchors with a URL of work.aspx?subsection=24&project=15.

How can I开发者_StackOverflow社区 prevent that from happening?


The only solution I can think of is to use regexes; something like this:

$('subnav').getElements('a').filter(function (element, index) {
    return /work\.aspx\?subsection=24&project=1(?:$|&)/.test(element.href);
});

That regex will match project=1 and then either a & or the end of the string. It uses MooTool's (or the native browser's) Array.filter to remove all non-matches. It isn't the most elegant solution, especially if you are using this dynamically, since then you'd have to write some code to create a new regex.


Going to answer my own question. It was as simple as changing the * to a $.

$('subnav').getElements('a[href$=/'+href+']')


Sounds like this should be handled more gracefully by a 301 or 302 redirect...

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜