2011-09-27 31 views
1

我在某個url上爲我的菜單創建了一個活動狀態。我的網址是這樣的:使用標記href匹配url文件夾以使其處於活動狀態

  • /products/other-clothing/sporting/adults-anzac-australia-polo
  • /products/other-clothing/sporting/adults-nz-tee
  • /products/bags/backpacks

我的代碼從/因此其他服裝,運動後得到的文件夾等 它工作正常,我只是假設有一個更有效的方法來編寫代碼。

這裏是我的代碼:

jQuery(".product-nav li a").each(function() { 
    // URL url 
    var cat = location.pathname.split("/")[2]; 
    var subcat = location.pathname.split("/")[3]; 
    var c = "/products/" + cat + "/" + subcat; 

    // A tag url 
    var acat = this.href.split("/")[4]; 
    var asubcat = this.href.split("/")[5]; 
    var e = "/products/" + acat + "/" + asubcat; 

    if(e == c) { 
    jQuery(this).parent().addClass("active"); 
    jQuery(this).parent().parent().parent().addClass("active"); 
    } 
}); 

如果任何人都可以提供寫那簡直太好了代碼的更清潔的方式。我可能不需要"/products/" +

回答

1

這裏有一個簡單的重擊吧:

jQuery(".product-nav li a").each(function() { 
    // URL url 
    var c = location.pathname.split('/').slice(2, 4) 
    // A tag url 
    , e = this.href.split('/').slice(4, 6) 
    ; 

    if(e[0] == c[0] && e[1] == c[1]) { 
    jQuery(this).parentsUntil(
     'div:not(.subnav)', // go up the tree until the 1st div that isn't .subnav 
     '.product-nav li, .subnav' // and only match these parents 
    ).addClass('active'); 
    } 
}); 

.parent().parent().parent()...有一個非常糟糕的代碼氣味,但不看看你的標記不能得到改善。您應該使用.closest()來代替。

+0

您不能比較那樣的數組! :) –

+0

正確的你,丹尼爾。當您發佈您的評論時,我正在修復它。 ;) –

+0

這可能看起來更好,更短,感謝您的意見我將盡力實施這個明天:-) – Luke

0

有趣的問題。這是我試圖把它清理乾淨:

jQuery(function ($) { 
    function Category(outer, inner) { 
    this.outer = outer 
    this.inner = inner 
    } 

    Category.fromURL = function (url) { 
    var parts = url.replace(/^(https?:\/\/.*?)?\//, "").split("/") 

    return new Category(parts[1], parts[2]) 
    } 

    Category.prototype.equals = function (other) { 
    return this.outer === other.outer 
     && this.inner === other.inner 
    } 

    var category = Subcategory.fromURL(location.href) 

    $(".product-nav a").each(function() { 
    if (Category.fromURL(this.href).equals(category)) { 
     $(this).closest("li.inner").addClass("active") 
     $(this).closest("li.outer").addClass("active") 
    } 
    }) 
}) 
3

注意下列用語的輸出:

$('<a href="https://stackoverflow.com/questions/7564539/match-url-folders-with-a-tag-href-to-make-a-active-state"></a>')[0].href; 
/* 
* http://stackoverflow.com/questions/7564539/match-url-folders-with-a-tag-href-to-make-a-active-state 
*/ 
$('<a href="https://stackoverflow.com/questions/7564539/match-url-folders-with-a-tag-href-to-make-a-active-state"></a>').eq(0).attr('href'); 
/* 
* /questions/7564539/match-url-folders-with-a-tag-href-to-make-a-active-state 
*/ 

因此,如果您<a>標籤中包含有/開頭的網址,你可以比較.attr('href')location.pathname。要進行測試,請嘗試在此頁的控制檯中運行此操作:

$('a').each(function() { 
    if ($(this).attr('href') == location.pathname) { 
     $(this).css({ 
      'font-size': '40px', 
      'background-color': 'lime' 
     }); 
    } 
}); 
+0

有趣的觀察! –

相關問題