복붙노트

[JQUERY] 메뉴에서 .active는 jQuery를 추가 기능 클래스

JQUERY

메뉴에서 .active는 jQuery를 추가 기능 클래스

해결법


  1. 1.jsFiddle에서 솔루션 여기를 클릭하십시오

    jsFiddle에서 솔루션 여기를 클릭하십시오

    당신이 필요한 것은 당신이 언급 한 바와 같이 window.location.pathname을 얻을 후 및 탐색하는 HREF에 대한 테스트를에서 정규 표현식을 만들 필요가있다.

    $(function(){
    
        var url = window.location.pathname, 
            urlRegExp = new RegExp(url.replace(/\/$/,'') + "$"); // create regexp to match current url pathname and remove trailing slash if present as it could collide with the link in navigation in case trailing slash wasn't present there
            // now grab every link from the navigation
            $('.menu a').each(function(){
                // and test its normalized href against the url pathname regexp
                if(urlRegExp.test(this.href.replace(/\/$/,''))){
                    $(this).addClass('active');
                }
            });
    
    });
    

  2. 2.나를 위해 쉬운 방법이었다 :

    나를 위해 쉬운 방법이었다 :

    var activeurl = window.location;
    $('a[href="'+activeurl+'"]').parent('li').addClass('active');
    

    내 링크가 절대 URL로 이동 때문에 링크가 상대적인 경우,하지만 당신은 사용할 수 있습니다 :

     window.location**.pathname**
    

  3. 3.href를을 확인을 통해 LI 요소, 루프를 가져 오기 :

    href를을 확인을 통해 LI 요소, 루프를 가져 오기 :

    $('.menu').find('a').each(function() {
        if($(this).attr('href').indexOf('www.xyz.com/other/link1/')>0) {
              $(this).addClass('active');
        }
    })
    

  4. 4.이 WORKS에서이 옵션을 선택합니다

    이 WORKS에서이 옵션을 선택합니다

    html로

    <div class="menu">
    
        <ul>
            <li><a href="~/link1/">LINK 1</a>
            <li><a href="www.xyz.com/other/link1">LINK 2</a>
            <li><a href="~/link3/">LINK 3</a>
        </ul>
    
    </div>
    

    JQuery와

    $(document).ready(function(){
        $(".menu ul li a").each(function(){
            if($(this).attr("href")=="www.xyz.com/other/link1")
                $(this).addClass("active");
        })
    })
    

  5. 5.몇 게시물 여기에서 최대 Wasim의 대답은 광고로 작동합니다 :

    몇 게시물 여기에서 최대 Wasim의 대답은 광고로 작동합니다 :

    http://jsfiddle.net/Realto619/jKf3F/1/


  6. 6.이 제외한 메뉴에 '는'요소에 클래스를 추가 할 때 다른 "addClass"방법은 나를 위해 일한 :

    이 제외한 메뉴에 '는'요소에 클래스를 추가 할 때 다른 "addClass"방법은 나를 위해 일한 :

    $(function () {
            var url = window.location.pathname,
        urlRegExp = new RegExp(url.replace(/\/$/, '') + "$");  
            $('a').each(function () {
                                if (urlRegExp.test(this.href.replace(/\/$/, ''))) {
                    $(this).addClass('active');
                }
            });
        });
    

    이 그것을 찾기 위해 나 네 시간이 걸렸다.


  7. 7.window.location.href는 당신에게 현재의 URL를 (같은 브라우저의 주소 표시)을 제공 할 것입니다. 관련 부분을 분석하고 검색 한 후 각 링크 HREF과 비교 것이며, 해당 링크에 활성 클래스를 지정합니다.

    window.location.href는 당신에게 현재의 URL를 (같은 브라우저의 주소 표시)을 제공 할 것입니다. 관련 부분을 분석하고 검색 한 후 각 링크 HREF과 비교 것이며, 해당 링크에 활성 클래스를 지정합니다.


  8. 8.사용 window.location.pathname와는 링크와 비교. 당신이 뭔가를 할 수 있습니다 :

    사용 window.location.pathname와는 링크와 비교. 당신이 뭔가를 할 수 있습니다 :

    $('a[href="~/' + currentSiteVar + '/"').addClass('active');
    

    하지만 먼저 당신이 선택에 넣어하기 위해 현재 SiteVar를 준비해야합니다.


  9. 9.난 당신이 ASP 코드와 JS 코드를 혼합하려고하고 어떤 점에서이 파손되거나 제대로 바인딩 호출을 변명 아니에요 추측하고있다.

    난 당신이 ASP 코드와 JS 코드를 혼합하려고하고 어떤 점에서이 파손되거나 제대로 바인딩 호출을 변명 아니에요 추측하고있다.

    아마 당신은 대신 대리인을 사용하여 시도 할 수 있습니다. 그것은 클릭 이벤트를 바인딩 할 때의 복잡성을 잘라 것입니다.

    예제는 다음과 같습니다

    $('body').delegate('.menu li','click',function(){
       var $li = $(this);
    
       var shouldAddClass = $li.find('a[href^="www.xyz.com/link1"]').length != 0;
    
       if(shouldAddClass){
           $li.addClass('active');
       }
    });
    

    그 도움이된다면 그것은 jQuery를에서 선택기 속성의 시작을 사용하십시오.

    경비


  10. 10.나를 위해이 작품 : D

    나를 위해이 작품 : D

        function setActive() {
          aObj = document.getElementById('menu').getElementsByTagName('a');
          for(i=0;i<aObj.length;i++) {
            if(document.location.href.indexOf(aObj[i].href)>=0) {
              var activeurl = window.location;
              $('a[href="'+activeurl+'"]').parent('li').addClass('active');
            }
          }
        }
    
        window.onload = setActive;
    

  11. 11.

    <script type="text/javascript">
        jQuery(document).ready(function($) {
        var url = window.location.pathname,
    urlRegExp = new RegExp(url.replace(/\/$/,'') + "$"); 
        $("#navbar li a").each(function() {//alert('dsfgsdgfd');
        if(urlRegExp.test(this.href.replace(/\/$/,''))){
        $(this).addClass("active");}
    });
    }); 
    </script>
    

  12. 12.활성 메뉴 설정, 그들은 그렇게 할 수있는 많은 방법이있다. 지금, 나는 당신에게 CSS에 의해 활성 메뉴를 설정하는 방법을 공유 할 수 있습니다.

    활성 메뉴 설정, 그들은 그렇게 할 수있는 많은 방법이있다. 지금, 나는 당신에게 CSS에 의해 활성 메뉴를 설정하는 방법을 공유 할 수 있습니다.

        <a href="index.php?id=home">Home</a>
        <a href="index.php?id=news">News</a>
        <a href="index.php?id=about">About</a>
    

    이제, 당신은 단지 _request는 [ "ID"] == "홈"티 에코 "클래스 = '활성'", 우리는 다른 사람과 동일 할 수있다 $ 설정합니다.

    <a href="index.php?id=home" <?php if($_REQUEST["id"]=="home"){echo "class='active'";}?>>Home</a>
    <a href="index.php?id=news" <?php if($_REQUEST["id"]=="news"){echo "class='active'";}?>>News</a>
    <a href="index.php?id=about" <?php if($_REQUEST["id"]=="about"){echo "class='active'";}?>>About</a>
    

    나는 당신과 함께 유용하다 생각합니다.


  13. 13.

    $(function() {
         var pgurl = window.location.href.substr(window.location.href.lastIndexOf("/")+1);
         $(".nav li").each(function(){
              if($('a',this).attr("href") == pgurl || $('a', this).attr("href") == '' )
              $(this).addClass("active");
         })
    });
    

  14. 14.나를 위해이 작품, 기본적으로 탐색은 동일

    나를 위해이 작품, 기본적으로 탐색은 동일

    <div id="main-menu">
      <ul>
        <li><a href="<?php echo base_url();?>shop">SHOP</a>
        <li><a href="<?php echo base_url();?>events">EVENTS</a>
        <li><a href="<?php echo base_url();?>services">SERVICES</a>
      </ul>
    </div>
    

    의 당신이 URL에있어 가정 해 봅시다 : 에 http : // localhost를 / 프로젝트 이름 / 숍 / detail_shop /

    그리고 당신은 당신이 당신이 "detail_shop"에서 "가게"의 서브 페이지에있을 경우에도, 활성 탐색의 표시를 시각적 수 있도록 "SHOP"리 링크 클래스 "활성"싶어.

    자바 스크립트 :

    var path = window.location.pathname;
    var str = path.split("/");
    var url = document.location.protocol + "//" + document.location.hostname + "/" + str[1] + "/" + str[2];
    
    $('#main-menu a[href="' + url + '"]').parent('li').addClass('active');
    

    기본적으로 그 href 속성이 "가게"로 시작 년대 탐색 링크와 일치합니다 (또는 보조 디렉토리가 될 일이 무엇이든).


  15. 15.

        let path = window.location.href;
        $('#nav li a').each(function() {
            if (this.href === path) {
                $(this).addClass('activo');
            }else{
                $(this).removeClass('activo')
            }
            
        })
        
    
  16. from https://stackoverflow.com/questions/4866284/jquery-add-class-active-on-menu by cc-by-sa and MIT license