繁体   English   中英

jQuery Javascript菜单导航添加删除类

[英]jQuery Javascript Menu Navigation add remove class

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

我尝试了不同的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");
});}

效果很好,但是就像我提到的那样,我不明白如何集成添加或查找URL开头为www.example.com时是否存在默认类,我会将当前类添加到index.html

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

通过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