【问题标题】:jQuery Javascript Menu Navigation add remove classjQuery Javascript 菜单导航添加删除类
【发布时间】:2012-12-11 13:45:01
【问题描述】:

当站点为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

【问题讨论】:

    标签: javascript jquery menu navigation


    【解决方案1】:

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

    【讨论】:

      【解决方案2】:

      通过 a 标签上的 href 外观,您将要检查 pathname

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

      【讨论】:

      • 感谢 location.pathname 在我尝试将 href 与它进行比较时似乎不起作用。我正在使用上面的方法。虽然欢呼
      猜你喜欢
      • 1970-01-01
      • 2017-11-21
      • 1970-01-01
      • 1970-01-01
      • 2018-11-13
      • 2019-12-14
      • 1970-01-01
      • 2014-02-25
      • 1970-01-01
      相关资源
      最近更新 更多