2012-12-19 43 views
0

我試圖讓雙層導航工作。一切都很酷,但jQuery根據URL的內容將類current設置爲正確的元素。但是,即使警報沒有工作,我不知道爲什麼(新的jQuery)。使用jquery在A元素中設置類的URL路徑

,因爲它是目前:Remote Test Site

$(document).ready(function(){ 

    // url 
    var $path = location.pathname.split("/"); 
    var $topnav_path = path[1]; 
    var $filternav_path = path[2]; 

    // current page 
    var $test = "the category is: " + $topnav_path + " AND the filter is: " + $filternav_path; 
    alert($test); 

    // navigation 
    $(function() { 
     // set link to current page 
     if ($path[1]) { 
      $('#top_nav a[class$="' + $topnav_path + '"]').toggleClass('current'); 
     } 
     // if link is root, set first child (home) 
     if (!$path[1]) { 
      $('#top_nav a:first').toggleClass('current'); 
     } 

     // set filter to current filter 
     if ($path[2]) { 
      $('#filter_nav a[class$="' + $filternav_path + '"]').toggleClass('current'); 
     } 
     // if link is root, set first child (home) 
     if (!$path[2]) { 
      $('#filter_nav a:first').toggleClass('current'); 
     } 
    }); 
}); 

下,按照下面的第一個答案,也無法正常工作(帶或不帶函數調用):

$(document).ready(function(){ 

    // url 
    var path = location.pathname.split("/"), 
     topnav_path = path[1] != undefined ? path[1] : false, 
     filternav_path = path[2] != undefined ? path[2] : false; 

    // test url 
    var test = "the category is: " + topnav_path + " AND the filter is: " + filternav_path; 
    alert(test); 

    // navigation 
    $(function() { 
     // set top nav to current category or home 
     if (path[1]) { 
      $('#top_nav a[class$="' + topnav_path + '"]').toggleClass('current'); 
     }else{ 
      $('#top_nav a:first').toggleClass('current'); 
     } 
     // set filter nav to current filter or all 
     if (path[2]) { 
      $('#filter_nav a[class$="' + filternav_path + '"]').toggleClass('current'); 
     }else{ 
      $('#filter_nav a:first').toggleClass('current'); 
     } 
    }); 
});​ 
+0

至少警報應該打印出來的東西..但它不工作! – obmon

回答

2

有沒有$test變量,你把它命名爲test。其他變量也一樣。

$(document).ready(function(){ 
    var path = location.pathname.split("/"), 
     topnav_path = path[1] != undefined ? path[1] : false, 
     filternav_path = path[2] != undefined ? path[2] : false; 

    var test = "the category is: " + topnav_path + " AND the filter is: " + filternav_path; 

    if (path[1]) { 
     $('#top_nav a[class$="' + topnav_path + '"]').toggleClass('current'); 
    }else{ 
     $('#top_nav a:first').toggleClass('current'); 
    } 

    if (path[2]) { 
     $('#filter_nav a[class$="' + filternav_path + '"]').toggleClass('current'); 
    }else{ 
     $('#filter_nav a:first').toggleClass('current'); 
    } 
});​ 
+0

哎呀..粘貼錯誤。我編輯了原始評論。 – obmon

+0

試過你的代碼..沒有$標誌和更清潔,但仍然無法正常工作..甚至沒有警報。 – obmon

+0

立即試用.---- – adeneo