Programing

Twitter 부트 스트랩-탭-URL이 변경되지 않음

lottogame 2020. 8. 12. 22:08
반응형

Twitter 부트 스트랩-탭-URL이 변경되지 않음


저는 Twitter Bootstrap과 "탭"을 사용하고 있습니다.

다음 코드가 있습니다.

<ul class="nav nav-tabs">
    <li class="active"><a data-toggle="tab" href="#add">add</a></li>
    <li><a data-toggle="tab" href="#edit" >edit</a></li>
    <li><a data-toggle="tab" href="#delete" >delete</a></li>
</ul>

탭은 제대로 작동하지만 URL에 #add, #edit, #delete가 추가되지 않았습니다.

data-toggleURL 변경을 제거 했지만 탭이 작동하지 않습니다.

이것에 대한 해결책이 있습니까?


이 코드를 사용해보십시오. URL에 탭 href를 추가하고 페이지로드시 해시를 기반으로 탭을 엽니 다.

$(function(){
  var hash = window.location.hash;
  hash && $('ul.nav a[href="' + hash + '"]').tab('show');

  $('.nav-tabs a').click(function (e) {
    $(this).tab('show');
    var scrollmem = $('body').scrollTop() || $('html').scrollTop();
    window.location.hash = this.hash;
    $('html,body').scrollTop(scrollmem);
  });
});

완전한 솔루션에 필요한 세 가지 구성 요소가 있습니다.

  1. URL에 해시가있는 경우 페이지가로드 될 때 올바른 탭을 표시합니다.
  2. 탭이 변경 될 때 URL의 해시를 변경합니다.
  3. URL에서 해시가 변경되면 탭을 변경하고 (뒤로 / 앞으로 버튼) 첫 번째 탭이 올바르게 순환되는지 확인합니다.

여기에 언급 된 의견이나 수용된 답변이 이러한 모든 시나리오를 처리한다고 생각하지 않습니다.

꽤 많이 관련되어 있기 때문에 작은 jQuery 플러그인으로 가장 적합하다고 생각합니다 : https://github.com/aidanlister/jquery-stickytabs

다음과 같이 플러그인을 호출 할 수 있습니다.

$('.nav-tabs').stickyTabs();

이에 대한 블로그 게시물을 만들었습니다. http://aidanlister.com/2014/03/persisting-the-tab-state-in-bootstrap/


를 사용 하면 플러그인이 탭을 처리 data-toggle="tab" 하도록 요청 하며, 탭을 처리하는 동안 preventDefault이벤트 ( github의 코드)를 호출 합니다 .

자신의 탭 활성화를 사용하고 이벤트가 진행되도록 할 수 있습니다.

$('.nav-tabs a').click(function (e) {
    // No e.preventDefault() here
    $(this).tab('show');
});

그리고 속성을 제거해야합니다. data-toggle="tab"

의심스러운 점이 있으면 문서를 확인하십시오 .


앵커 요소가 이미 URL 해시를 변경하므로 onhashchange 이벤트를 수신하는 것도 좋은 옵션입니다. @flori가 이미 언급했듯이이 방법은 브라우저 뒤로 버튼과 함께 잘 작동합니다.

var tabs$ = $(".nav-tabs a");

$( window ).on("hashchange", function() {
    var hash = window.location.hash, // get current hash
        menu_item$ = tabs$.filter('[href="' + hash + '"]'); // get the menu element

    menu_item$.tab("show"); // call bootstrap to show the tab
}).trigger("hashchange");

마지막으로 리스너를 정의한 직후에 이벤트를 트리거하면 페이지로드시 올바른 탭을 표시하는 데 도움이됩니다.


귀하의 문제에 대한 나의 해결책 :

먼저 다음과 같이 data-valuea링크 에 새 속성을 추가 합니다.

<ul class="nav nav-tabs">
    <li class="active">
        <a data-toggle="tab" href="#tab-add" data-value="#add">add</a>
    </li>
    <li>
        <a data-toggle="tab" href="#tab-edit" data-value="#edit">edit</a>
    </li>
    <li>
        <a data-toggle="tab" href="#tab-delete" data-value="#delete">delete</a>
    </li>
</ul>

둘째, 탭의 ID를 변경 (예 :에서 add로) tab-add하고 tab-접두사 를 포함하도록 href도 업데이트 합니다.

<div class="tab-content">
    <div class="tab-pane" id="tab-add">Add panel</div>
    <div class="tab-pane" id="tab-edit">Edit panel</div>
    <div class="tab-pane" id="tab-delete">Panel panel</div>
</div>

그리고 마지막으로 js 코드 :

<script type="text/javascript">
    $(function () {
        var navTabs = $('.nav-tabs a');
        var hash = window.location.hash;
        hash && navTabs.filter('[data-value="' + hash + '"]').tab('show');

        navTabs.on('shown', function (e) {
            var newhash = $(e.target).attr('data-value');
            window.location.hash = newhash;
        });
    })
</script>

여기에 jsFiddle 이 있습니다. 그러나 jsFiddle에서 사용하는 iframe 때문에 작동하지 않지만 내 솔루션의 소스를 읽을 수 있습니다.


Bootstrap 3 탭을 사용하는 CakePHP와 동일한 문제가 있으며 외부 URL 및 앵커로 보낼 때 많은 솔루션을 검토 한 후 메뉴를 잃는 섹션으로 이동합니다.

덕분에 : http://ck.kennt-wayne.de/2012/dec/twitter-bootstrap-how-to-fix-tabs

$(document).ready(function()
 {  
//Redirecciona al tab, usando un prefijo al cargar por primera vez, al usar redirect en cake #_Pagos    
//Redirecciona al tab, usando #Pagos
/* Automagically jump on good tab based on anchor; for page reloads or links */
 if(location.hash) 
  {
     $('a[href=' + location.hash + ']').tab('show');         
  }


//Para evitar el bajar al nivel del tab, (al mostrarse el tab subimos)
$('a[data-toggle="tab"]').on('shown.bs.tab', function(e) 
{
    location.hash = $(e.target).attr('href').substr(1);
    scrollTo(0,0);      
});



//Actualiza el URL con el anchor o ancla del tab al darle clic
 /* Update hash based on tab, basically restores browser default behavior to
 fix bootstrap tabs */
$(document.body).on("click", "a[data-toggle]", function(event) 
  {
    location.hash = this.getAttribute("href");
  });


//Redirecciona al tab, al usar los botones de regresar y avanzar del navegador.
/* on history back activate the tab of the location hash if exists or the default tab if no hash exists */   
$(window).on('popstate', function() 
{
  //Si se accesa al menu, se regresa al tab del perfil (activo default), fixed conflict with menu
  //var anchor = location.hash || $("a[data-toggle=tab]").first().attr("href");
  var anchor = location.hash;
  $('a[href=' + anchor + ']').tab('show');

});   

});//Fin OnReady

해시 변경에 반응하는 간단한 방법도 있습니다 (예 : 뒤로 버튼). tomaszbak 솔루션에 hashchange 이벤트 리스너를 추가하기 만하면됩니다.

$(function(){
  // Change tab on load
  var hash = window.location.hash;
  hash && $('ul.nav a[href="' + hash + '"]').tab('show');

  $('.nav-tabs a').click(function (e) {
    $(this).tab('show');
    var scrollmem = $('body').scrollTop();
    window.location.hash = this.hash;
    $('html,body').scrollTop(scrollmem);
  });

  // Change tab on hashchange
  window.addEventListener('hashchange', function() {
    var changedHash = window.location.hash;
    changedHash && $('ul.nav a[href="' + changedHash + '"]').tab('show');
  }, false);
});

나는 Bootstrap 3.3. *을 사용하고 있으며 위의 솔루션 중 어느 것도 도움이되지 않았으며 답변 1로 표시되었습니다. 나는 방금 아래 스크립트를 추가하고 일했습니다.

$(function(){
    var hash = document.location.hash;
    if (hash) {
       $('.navbar-nav a[href="' + hash + '"]').tab('show');
    }
    $('a[data-toggle="tab"]').on('click', function (e) {
       history.pushState(null, null, $(this).attr('href'));
    });
});

이것이 도움이되기를 바랍니다.


여기에data-toggle="tab" 설명 된 문서화 된 구문을 사용한다고 가정하면 가장 간단 합니다 .

$(document).on('shown.bs.tab', function(event) {
  window.location.hash = $(event.target).attr('href');
});

For those using Ruby on Rails or any other server side script, you will want to use the anchor option on paths. This is because once the page loads, it does not have the URL hash available. You will want to supply the correct tab via your link or form submission.

<%= form_for @foo, url: foo_path(@foo, anchor: dom_id(foo)) do |f| %>
# Or
<%= link_to 'Foo', foo_path(@foo, anchor: dom_id(foo)) %>

If you are using a prefix to prevent the window from jumping to the id:

<%= form_for @foo, url: foo_path(@foo, anchor: "bar_#{dom_id(foo)}") do |f| %>

Then you CoffeeScript:

  hash = document.location.hash
  prefix = 'bar_'
  $('.nav-tabs a[href=' + hash.replace(prefix, '') + ']').tab 'show' if hash
  $('.nav-tabs a').on 'shown.bs.tab', (e) ->
    window.location.hash = e.target.hash.replace '#', '#' + prefix

Or JavaScript:

var hash, prefix;

hash = document.location.hash;
prefix = 'bar_';

if (hash) {
  $('.nav-tabs a[href=' + hash.replace(prefix, '') + ']').tab('show');
}

$('.nav-tabs a').on('shown.bs.tab', function(e) {
  window.location.hash = e.target.hash.replace('#', '#' + prefix);
});

This should work in Bootstrap 3.


Thanks to @tomaszbak for the original solution however since my edits got rejected and I'm unable to comment on his post yet I will leave my slightly improved and more readable version here.

It does basically the same thing but if fixes the cross browser compatibility issue I had with his.

$(document).ready(function(){
   // go to hash on window load
   var hash = window.location.hash;
   if (hash) {
       $('ul.nav a[href="' + hash + '"]').tab('show');
   }
   // change hash on click
   $('.nav-tabs a').click(function (e) {
       $(this).tab('show');
       if($('html').scrollTop()){
           var scrollmem = $('html').scrollTop(); // get scrollbar position (firefox)
       }else{
           var scrollmem = $('body').scrollTop(); // get scrollbar position (chrome)
       }
       window.location.hash = this.hash;
       $('html,body').scrollTop(scrollmem); // set scrollbar position
   });
});

Here's an option using history.pushState so that you can use your browser history to go back to a previous tab

  $(document).ready(function() {
  // add a hash to the URL when the user clicks on a tab
  $('a[data-toggle="tab"]').on('click', function(e) {
    history.pushState(null, null, $(this).attr('href'));
  });
  // navigate to a tab when the history changes
  window.addEventListener("popstate", function(e) {
    var activeTab = $('[href=' + location.hash + ']');
    if (activeTab.length) {
      activeTab.tab('show');
    } else {
      $('.nav-tabs a:first').tab('show');
    }
  });
});

None of the above worked for me, so here's my how I got mine working:

  1. Add class="tab-link" to all links needing this functionality
  2. Add the following code to your javascript:
    window.addEventListener
    (
        'popstate',
        function( event )
        {
            tab_change();
        }
    );

    function tab_change()
    {
        var hash = window.location.hash;
        hash && $( 'ul.nav a[href="' + hash + '"]' ).tab( 'show' );

        $( '.tab-link' ).click
        (
            function( e )
            {
                $( this ).tab( 'show' );

                var scrollmem = $( 'body' ).scrollTop() || $( 'html' ).scrollTop();
                window.location.hash = this.hash;
                $( 'html,body' ).scrollTop( scrollmem );

                $( 'ul.nav-tabs a[href="' + window.location.hash + '"]' ).tab( 'show' );
            }
        );
    }


This also fixes an extremely obscure tab a href not firing when using jquery and bootstrap

<script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script> 

<script type="text/javascript">
$('.nav-tabs a').click(function (e) {
    // No e.preventDefault() here.
    $(this).tab('show');
});
</script>

<script src="//netdna.bootstrapcdn.com/twitter-bootstrap/2.2.1/js/bootstrap.min.js"></script>

참고URL : https://stackoverflow.com/questions/12131273/twitter-bootstrap-tabs-url-doesnt-change

반응형