2011-09-27 2 views
1

특정 URL에서 내 메뉴의 활성 상태를 만들었습니다. 나는이 같은 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

맞습니다, Daniel. 나는 당신이 당신의 코멘트를 올릴 때 그것을 고치고 있었다. ;) –

+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> 태그 /로 시작하는 URL을 포함하는 경우

$('<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 
*/ 

그래서, 당신은 .attr('href')와 비교할 수 여기를 정리하는 나의 시도는 location.pathname. 테스트하려면이 페이지의 콘솔에서 다음을 실행하십시오 :

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

재미있는 관찰! –

관련 문제