简体   繁体   English

jQuery Javascript菜单导航添加删除类

[英]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. 当网站为www.example.com并加载index.html ,导航将不会预先选择要显示的主页。 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. 我有一个功能,该功能填充菜单,另一个功能是获取当前页面以添加循环的类,我知道当站点为www.example.com时,找不到index.html页面将其更改为当前类。

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. 我尝试了不同的if语句,并尝试在li放置默认类,即<li><a href='index.html' class='current'>Home</a></li>但它将同时显示此内容和任何内容我访问的其他页面。

/*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 效果很好,但是就像我提到的那样,我不明白如何集成添加或查找URL开头为www.example.com时是否存在默认类,我会将当前类添加到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 通过a标记上href的外观,您需要对照pathname进行检查

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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