当我刷新页面/为我的Django应用提交表单时,它总是转到第一个选项卡,而不是重定向到用户当前所在的选项卡。有没有简单的解决方法,因为我没有在线找到答案
答案 0 :(得分:0)
您可以将标签选择保存到sessionStorage
,并在页面加载时使用它。如果您使用Bootstrap(和jQuery)并遵循其basic guidelines,则应使用如下代码来完成这项工作:
// Save last active tab to sessionStorage
$('a[data-toggle="tab"]').on('shown.bs.tab', function () {
try {
sessionStorage.setItem('lastTab', $(this).attr('href'));
} catch (error) {
console.log(error);
}
});
...,这将转到页面加载时的最后一个活动标签:
// Get last active tab from sesssionStorage and go there
var lastTab = sessionStorage.getItem('lastTab');
if (lastTab) {
$('[href="' + lastTab + '"]').tab('show');
}
使用此代码时应注意的一件事是,您使用唯一的标签ID。
将此内容包含在Django模板中,您可以在其中使用以下导航选项卡:
{% block extrahead %}
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css" integrity="sha384-MCw98/SFnGE8fJT3GXwEOngsV7Zt27NXFoaoApmYm81iuXoPkFOJwJ8ERdknLPMO" crossorigin="anonymous">
<script src="https://code.jquery.com/jquery-3.3.1.slim.min.js" integrity="sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.3/umd/popper.min.js" integrity="sha384-ZMP7rVo3mIykV+2+9J3UJ46jBk0WLaUAdn689aCwoqbBJiSnjAK/l8WvCWPIPm49" crossorigin="anonymous"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/js/bootstrap.min.js" integrity="sha384-ChfqqxuZUCnJSK3+MXmPNIyE6ZbWh2IMqE241rYiqJxyMiZ6OW/JmZQ5stwEULTy" crossorigin="anonymous"></script>
<script>
$(document).ready( function() {
// Save last active tab to sessionStorage
$('a[data-toggle="tab"]').on('shown.bs.tab', function () {
try {
sessionStorage.setItem('lastTab', $(this).attr('href'));
} catch (error) {
console.log(error);
}
});
// Get last active tab from sesssionStorage and go there
var lastTab = sessionStorage.getItem('lastTab');
if (lastTab) {
$('[href="' + lastTab + '"]').tab('show');
}
)};
</script>
{% endblock %}
{% block content %}
<ul class="nav nav-tabs" id="myTab" role="tablist">
<li class="nav-item">
<a class="nav-link active" id="home-tab" data-toggle="tab" href="#home" role="tab" aria-controls="home" aria-selected="true">Home</a>
</li>
<li class="nav-item">
<a class="nav-link" id="profile-tab" data-toggle="tab" href="#profile" role="tab" aria-controls="profile" aria-selected="false">Profile</a>
</li>
<li class="nav-item">
<a class="nav-link" id="contact-tab" data-toggle="tab" href="#contact" role="tab" aria-controls="contact" aria-selected="false">Contact</a>
</li>
</ul>
<div class="tab-content" id="myTabContent">
<div class="tab-pane fade show active" id="home" role="tabpanel" aria-labelledby="home-tab">...</div>
<div class="tab-pane fade" id="profile" role="tabpanel" aria-labelledby="profile-tab">...</div>
<div class="tab-pane fade" id="contact" role="tabpanel" aria-labelledby="contact-tab">...</div>
</div>
{% endblock %}