Bootstrap-标签-网址不变

我用的是 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-toggle后,URL 会发生变化,但选项卡不起作用。

有什么解决办法吗?

93615 次浏览

Using data-toggle="tab" 问道 the plugin to handle the tabs, which while doing it calls preventDefault on the event (Github 上的代码).

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

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

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

如果您有疑问,请检查 医生

试试这段代码,它根据页面加载的散列表将 tab href 添加到 url + open tab 中:

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

这还修复了一个非常隐蔽的选项卡,当使用 jquery 和 bootstrap 时 href 不会触发该选项卡

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

我来解决你的问题:

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

<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,也更新 href 以包含 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>

最后是 js code:

<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-但它不工作,因为 iframe 使用 jsFiddle,但您可以阅读我的解决方案的源代码。

还有一个简单的方法来应对散列变化(例如后退按钮)。只需在 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);
});

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

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

Most simple, assuming you're using the documented data-toggle="tab" syntax described 给你:

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

一个完整的解决方案需要三个组成部分:

  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

你可以这样调用插件:

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

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

对于那些使用 RubyonRails 或任何其他服务器端脚本的用户,您需要在路径上使用 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)) %>

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

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

然后是咖啡剧本:

  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

或者 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);
});

这个应该可以在 Bootstrap 3中使用。

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

感谢: 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的原始解决方案,然而,因为我的编辑被拒绝,我无法评论他的文章,但我会留下我的略有改进,更可读的版本在这里。

它基本上做同样的事情,但如果修复的跨浏览器兼容性问题,我与他的。

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

这里有一个使用 history.pushState的选项,这样您就可以使用浏览器历史记录返回到以前的选项卡

  $(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. class="tab-link"添加到所有需要此功能的链接
  2. 在你的 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' );
}
);
}


我正在使用 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'));
});
});

希望这个能帮到你。

我理解 OP 说的使用 JQuery,但是你可以简单地使用普通的 JS 来做到这一点:

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