开发者

jQuery: Finding a particular HREF Link

Basically the idea is to find out what the current location is of the document and change the class of the link (navigation accordion) to be changed. So far I have this below it works if the pageURL (variable) is the actual link but I do not want to create a whole list of possible links hence the $(location).att('href');

$(document).ready(function() {
    var pageURL = $(location).attr('href');
    $('a[href=pageURL]').attr('class', 'active');
});

Any help from any one would be greatly appreciated

Than开发者_Python百科ks in advance


You need to concatenate the variable into the selector string.

$('a[href=' + pageURL + ']').attr('class', 'active'); });

The way you had it, "pageURL" was simply part of the selector, so jQuery was looking for <a> elements with "pageURL" for the href attribute.

Also, I don't know what the location variable represents, but if you're looking for the current window location, you need a different approach.


By writing 'a[href=pageURL]', you are searching for a elements with href attributes equal to the literal pageURL, not the contents of the variable.
Instead, you need to concatenate the contents of the variable into the selector string.

For example:

$('a[href*="' + location.pathname + '"]').attr('class', 'active');

There's no point in using jQuery to access location.href.
Writing location.pathname will make it work even if the link doesn't include a domain name.
Using the [href*=...] selector matches elements with href attributes that contain the string.


The correct syntax is:

$('a[href=' + pageURL + ']').attr('class', 'active'); });
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜