jQuery Twitter Bootstrap - 标签 - URL 不会改变

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/12131273/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 11:21:06  来源:igfitidea点击:

Twitter Bootstrap - Tabs - URL doesn't change

jquerytwitter-bootstrap

提问by Ivanka Todorova

I'm using Twitter Bootstrap and its "tabs".

我正在使用 Twitter Bootstrap 及其“标签”。

I have the following code:

我有以下代码:

<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>

The tabs work properly, but the in the URL is not added the #add, #edit, #delete.

选项卡工作正常,但未在 URL 中添加 #add、#edit、#delete。

When I remove data-togglethe URL changes, but the tabs don't work.

当我删除data-toggleURL 更改时,但选项卡不起作用。

Any solutions for this?

对此有任何解决方案吗?

回答by tomaszbak

Try this code. It adds tab href to url + opens tab based on hash on page load:

试试这个代码。它将标签 href 添加到 url + 根据页面加载时的哈希打开标签:

$(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);
  });
});

回答by Aidan

There are three components necessary for a complete solution:

完整的解决方案需要三个组件:

  1. Show the correct tab when the page is loaded if there is a hash in the URL.
  2. Changing the hash in the URL when the tab is changed.
  3. Change the tab when the hash changes in the URL (back / forward buttons), and make sure the first tab is cycled correctly.
  1. 如果 URL 中有哈希值,则在页面加载时显示正确的选项卡。
  2. 更改选项卡时更改 URL 中的哈希值。
  3. 当 URL 中的哈希更改时更改选项卡(后退/前进按钮),并确保第一个选项卡正确循环。

I don't think any of the comments here, nor the accepted answer, handle all of these scenarios.

我认为这里的任何评论和公认的答案都不能处理所有这些情况。

As there's quite a bit involved, I think it's neatest as a small jQuery plugin: https://github.com/aidanlister/jquery-stickytabs

由于涉及相当多,我认为它作为一个小型 jQuery 插件是最简洁的:https: //github.com/aidanlister/jquery-stickytabs

You can call the plugin like so:

您可以像这样调用插件:

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

I've made a blog post for this, http://aidanlister.com/2014/03/persisting-the-tab-state-in-bootstrap/

我为此写了一篇博文,http://aidanlister.com/2014/03/persisting-the-tab-state-in-bootstrap/

回答by Sherbrow

Using data-toggle="tab"asksthe plugin to handle the tabs, which while doing it calls preventDefaulton the event (code on github).

Usingdata-toggle="tab"要求插件处理选项卡,它在执行时调用preventDefault事件(github上的代码)。

You can use your own tab activation, and let the event go through :

您可以使用自己的选项卡激活,并让事件通过:

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

And you must remove the attribute data-toggle="tab"

并且您必须删除该属性 data-toggle="tab"

Check the docif you have doubts.

如果您有疑问,请查看文档

回答by halilb

As your anchor elements already change the url hash, listening to onhashchangeevent is another good option. As @flori already mentioned, this method works nice with the browser back button.

由于您的锚元素已经更改了 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");

Finally, triggering the event just after you define the listener will also help showing the right tab on page load.

最后,在定义侦听器后立即触发事件也将有助于在页面加载时显示正确的选项卡。

回答by psulek

My solution to your problem:

我对你的问题的解决方案:

First add new data-valueattribute to each alink, like this:

首先data-value为每个a链接添加新属性,如下所示:

<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>

Second, change ids of tabs, e.g. from addto tab-add, also update hrefs to include tab-prefix:

其次,更改选项卡的 id,例如 from addto tab-add,还更新 hrefs 以包含tab-前缀:

<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>

And finally js code:

最后是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>

Here is jsFiddle- but it does not work because of iframe used by jsFiddle, but you can read source of my solution.

这是jsFiddle- 但由于 jsFiddle 使用了 iframe,它不起作用,但您可以阅读我的解决方案的源代码。

回答by Henry Gabriel González Montejo

Same problem with CakePHP with Bootstrap 3 Tabs, plus when i send with external URL and anchor, it jumps to the section losing my menu, after review many solutions made this...

CakePHP 与 Bootstrap 3 选项卡存在同样的问题,此外,当我使用外部 URL 和锚点发送时,它会跳转到丢失菜单的部分,在查看了许多解决方案后,这...

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

感谢: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

回答by Flori

There is also a simple way to react on hash changes (e.g. back button). Simply add an hashchange event listener to tomaszbak solution:

还有一种简单的方法可以对散列更改做出反应(例如后退按钮)。只需向 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);
});

回答by Abhimanyu

I am using Bootstrap 3.3.* and none of the above solution helped me, even marked as answer one. I just added below script and worked.

我正在使用 Bootstrap 3.3.* 并且上述解决方案都没有帮助我,甚至标记为答案一。我刚刚添加了下面的脚本并工作。

$(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'));
    });
});

Hope this helps you.

希望这对你有帮助。

回答by RousseauAlexandre

I understood that OP said using JQuery but you can simply use vanilla JS to do that:

我知道 OP 说使用 JQuery,但您可以简单地使用 vanilla JS 来做到这一点:

document.querySelectorAll('ul.nav a.nav-link').forEach(link => {
    link.onclick = () => window.history.pushState(null, null, link.attributes.href.value);
});

回答by Mohamad

For those using Ruby on Rails or any other server side script, you will want to use the anchoroption 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.

对于那些使用 Ruby on Rails 或任何其他服务器端脚本的人,您需要anchor在路径上使用该选项。这是因为一旦页面加载,它就没有可用的 URL 哈希。您需要通过链接或表单提交提供正确的选项卡。

<%= 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:

如果您使用前缀来防止窗口跳转到 id:

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

Then you CoffeeScript:

然后你 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:

或 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.

这应该适用于 Bootstrap 3。