简体   繁体   中英

jQuery Javascript Menu Navigation add remove class

When a site is www.example.com and loads index.html the navigation will not have preselected home to show. I have a function that populates the menu and another to get current page to add the class which loops and I know I can not find when the site is www.example.com the index.html page to change the class to be current.

I have tried different if statements and tried putting a default class in li ie <li><a href='index.html' class='current'>Home</a></li> but it would show both this and any other page I visit.

/*Navigation menu*/
function navMenu(){
document.writeln("<ul id='menu' class='menu'>");
document.writeln("<li><a href='index.html'>Home</a></li>"); 
document.writeln("<li><a href='myself.html'>About</a></li>");
document.writeln("<li><a href='portfolio.html'>Work</a></li>");
document.writeln("<li><a href='news.html'>News</a></li>");
document.writeln("<li><a href='contact.html'>Contact</a></li></ul>");   
}


function setActive() {
/*current page function*/
 $('#menu a').each(function(index) {
    if(this.href.trim() == window.location)
        $(this).addClass("current");
});}

This works fine but like I mentioned I don't understand how to integrate a add or finding if there was a default class at the start when the URL would be www.example.com I would add the current class to index.html

如果在调用/,时加载index.html /,只需将主页的href更改为/而不是index.html

By the looks of the href on the a tags you're going to want to check against the pathname

function setActive() {
/*current page function*/
 $('#menu a').each(function(index) {
    if(this.href.trim() == window.location.pathname)
        $(this).addClass("current");
});}

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