开发者

jQuery find link that matches current page

I have t开发者_如何学运维he following code that is trying to find a link that matches the current url: $item = $('ul#ui-ajax-tabs li a').attr('href', $(location).attr('pathname')); but instead it changes all the links to the current url :P

Can anyone help me fix it. Cheers


Use this query. Your code changes all href attributes of the selected links, rather than returning a selection of links with a matching href attribute:

$("a[href*='" + location.pathname + "']")

The [href*=..] selector returns a list of elements whose href attribute contains the current pathname.

Another method, return all elements whose href contains the current pathname. prop() is used instead of attr(), so that relative URLs are also correctly interpreted.

$item = $('ul#ui-ajax-tabs li a').filter(function(){
    return $(this).prop('href').indexOf(location.pathname) != -1;
});


Where URL format might change in Production like ASP.NET :/ this might work better if you ignore the end slash of URLs.

$('.mdl-navigation').find("a").filter(function () {
  return this.href.replace(/\/+$/, '') === window.location.href.replace(/\/+$/, '');
}).addClass('current-active-page-url');


That's because your CSS selector ul#ui-ajax-tabs li a matches more than one thing. Try being more specific with your selector, such as ul#ui-ajax-tabs li:first-child a.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜