加载时,变量pageName检查页面的html并存储当前页面的值。由于我使用的是Rails,因此我的Index.html页面出现问题,而我的Index是我的Root页面。因此,当我进入主页时,由于没有根页名称,因此运行document.location.href函数时会收到错误消息。

我试图进行错误检查,但不确定如何设置。感谢您的时间。如果您需要更多信息以帮助您,请给我发邮件。

$(document).ready(function() {

var pageName = document.location.href.match(/[^\/]+$/)[0];

if pageName.error() = true {
  $( ".navHome" ).addClass( "selectedPage" );
} else {
  switch (pageName) {
  case 'news':
    $( ".navNews" ).addClass( "selectedPage" );
    console.log("news");
    break;
  case 'media':
    $( ".navMedia" ).addClass( "selectedPage" );
    console.log("media");
    break;
  case 'about':
    $( ".navAbout" ).addClass( "selectedPage" );
    console.log("about");
    break;
  default:
    console.log("none");
   }
 };
});

最佳答案

我不确定您将JavaScript与什么混为一谈,但是语法错误,并且您遇到一个问题,即字符串没有error()方法,如果没有匹配项,您将无法引用第一个索引,因为没有数组。

因此,您需要更改引用匹配项的方式以及if语句的语法,而if语句则需要在该子句周围加上括号。

var pageName = document.location.href.match(/[^\/]+$/);  //Just run the match, no referencing the first index
if (!pageName) { //check if there is not a match with a falsey check (could use (pageName===null)
    $( ".navHome" ).addClass( "selectedPage" );
} else {
    switch (pageName[0]) {  //grab the match here, instead of in the reg exp line
        case 'news':
        break;
        /* rest of cases */
    }
}

10-07 19:34
查看更多