简体   繁体   中英

jquery if link = page url

ok pretty simple but i dont know how...

i just want to make an active state (probably just make it bold)

my menu is ul-li

i cant figure out how to write it so if the url matches with one of the links, make the link bold

please help

thanks for your time

Here's a short way to select links like that:

$('ul > li a[href$="' + window.location.pathname + '"]').css('font-weight','bold');

Or perhaps better like this, which does an exact match of both pathname attributes:

$('ul > li a[href]').filter(function() {
    return this.href.pathname === window.location.pathname;
}).css('font-weight','bold');

If you're using the full domain in the href , you could change it to:

return this.href === window.location;

Here is a great solution I have used:

$(function(){
       $("a").each(function(){
               if ($(this).attr("href") == window.location.pathname){
                       $(this).addClass("selected");
               }
       });
});

Source - https://css-tricks.com/snippets/jquery/highlight-all-links-to-current-page/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM