페이지 새로 고침 시 선택한 부트스트랩 탭을 유지하려면 어떻게 해야 합니까?
부트스트랩 3으로 새로 고칠 때 선택한 탭을 활성화하려고 합니다.이미 여기서 몇 가지 질문을 받고 시도하고 확인했지만 저는 할 일이 없습니다.제가 어디가 틀렸는지 모르겠습니다.여기 제 코드가 있습니다.
HTML
<!-- tabs link -->
<ul class="nav nav-tabs" id="rowTab">
<li class="active"><a href="#personal-info" data-toggle="tab">Personal Information</a></li>
<li><a href="#Employment-info" data-toggle="tab">Employment Information</a></li>
<li><a href="#career-path" data-toggle="tab">Career Path</a></li>
<li><a href="#warnings" data-toggle="tab">Warning</a></li>
</ul>
<!-- end: tabs link -->
<div class="tab-content">
<div class="tab-pane active" id="personal-info">
tab data here...
</div>
<div class="tab-pane" id="Employment-info">
tab data here...
</div>
<div class="tab-pane" id="career-path">
tab data here...
</div>
<div class="tab-pane" id="warnings">
tab data here...
</div>
</div>
Javascript:
// tab
$('#rowTab a:first').tab('show');
//for bootstrap 3 use 'shown.bs.tab' instead of 'shown' in the next line
$('a[data-toggle="tab"]').on('shown.bs.tab', function (e) {
//save the latest tab; use cookies if you like 'em better:
localStorage.setItem('selectedTab', $(e.target).attr('id'));
});
//go to the latest tab, if it exists:
var selectedTab = localStorage.getItem('selectedTab');
if (selectedTab) {
$('#'+selectedTab).tab('show');
}
선택한 탭을 창의 해시 값에 저장하는 것을 선호합니다.또한 "동일한" 페이지를 보는 동료에게 링크를 보낼 수 있습니다.다른 탭을 선택할 때 위치의 해시를 변경하는 것이 요령입니다.페이지에서 #을 이미 사용하는 경우 해시 태그를 분할해야 할 수 있습니다.제 앱에서는 ":"를 해시 값 구분 기호로 사용합니다.
<ul class="nav nav-tabs" id="myTab">
<li class="active"><a href="#home">Home</a></li>
<li><a href="#profile">Profile</a></li>
<li><a href="#messages">Messages</a></li>
<li><a href="#settings">Settings</a></li>
</ul>
<div class="tab-content">
<div class="tab-pane active" id="home">home</div>
<div class="tab-pane" id="profile">profile</div>
<div class="tab-pane" id="messages">messages</div>
<div class="tab-pane" id="settings">settings</div>
</div>
, 자바스크립트는 자바스크립트입니다.<script>...</script>
$('#myTab a').click(function(e) {
e.preventDefault();
$(this).tab('show');
});
// store the currently selected tab in the hash value
$("ul.nav-tabs > li > a").on("shown.bs.tab", function(e) {
var id = $(e.target).attr("href").substr(1);
window.location.hash = id;
});
// on load of the page: switch to the currently selected tab
var hash = window.location.hash;
$('#myTab a[href="' + hash + '"]').tab('show');
이것이 제가 시도한 최고의 것입니다.
$(document).ready(function() {
if (location.hash) {
$("a[href='" + location.hash + "']").tab("show");
}
$(document.body).on("click", "a[data-toggle='tab']", function(event) {
location.hash = this.getAttribute("href");
});
});
$(window).on("popstate", function() {
var anchor = location.hash || $("a[data-toggle='tab']").first().attr("href");
$("a[href='" + anchor + "']").tab("show");
});
다른 것들 사이의 혼합은 대답은 다음과 같습니다.
- 클릭 시 점프 금지
- 위치 해시 저장
- 로컬 스토리지 비용 절감(예: 양식 제출용)
복사&붙여넣기만 하면 됩니다 ;)
if (location.hash) { $('a[href=\'' + location.hash + '\']').tab('show'); } var activeTab = localStorage.getItem('activeTab'); if (activeTab) { $('a[href="' + activeTab + '"]').tab('show'); } $('body').on('click', 'a[data-toggle=\'tab\']', function (e) { e.preventDefault() var tab_name = this.getAttribute('href') if (history.pushState) { history.pushState(null, null, tab_name) } else { location.hash = tab_name } localStorage.setItem('activeTab', tab_name) $(this).tab('show'); return false; }); $(window).on('popstate', function () { var anchor = location.hash || $('a[data-toggle=\'tab\']').first().attr('href'); $('a[href=\'' + anchor + '\']').tab('show'); });
사비의 코드는 거의 완벽하게 작동했습니다.그러나 다른 페이지로 이동할 때 양식을 제출한 다음 탭이 있는 페이지로 리디렉션되는 경우 저장된 탭이 전혀 로드되지 않았습니다.
localStorage to the rescue (Nguyen의 코드를 약간 변경):
$('a[data-toggle="tab"]').click(function (e) {
e.preventDefault();
$(this).tab('show');
});
$('a[data-toggle="tab"]').on("shown.bs.tab", function (e) {
var id = $(e.target).attr("href");
localStorage.setItem('selectedTab', id)
});
var selectedTab = localStorage.getItem('selectedTab');
if (selectedTab != null) {
$('a[data-toggle="tab"][href="' + selectedTab + '"]').tab('show');
}
은 HTML5를 합니다.localStorage
탭을 합니다.
$('a[data-toggle="tab"]').on('shown.bs.tab', function(e) {
localStorage.setItem('activeTab', $(e.target).attr('href'));
});
var activeTab = localStorage.getItem('activeTab');
if (activeTab) {
$('#navtab-container a[href="' + activeTab + '"]').tab('show');
}
참조: http://www.tutorialrepublic.com/faq/how-to-keep-the-current-tab-active-on-page-reload-in-bootstrap.php https://www.w3schools.com/bootstrap/bootstrap_ref_js_tab.asp
음, 이것은 이미 2018년이지만, 나는 그것이 결코 하지 않는 것보다 늦은 것이라고 생각합니다(TV 프로그램의 제목처럼), 하하.아래는 제가 논문을 작성하는 jQuery 코드입니다.
<script type="text/javascript">
$(document).ready(function(){
$('a[data-toggle="tab"]').on('show.affectedDiv.tab', function(e) {
localStorage.setItem('activeTab', $(e.target).attr('href'));
});
var activeTab = localStorage.getItem('activeTab');
if(activeTab){
$('#myTab a[href="' + activeTab + '"]').tab('show');
}
});
</script>
부트스트랩 탭의 코드는 다음과 같습니다.
<div class="affectedDiv">
<ul class="nav nav-tabs" id="myTab">
<li class="active"><a data-toggle="tab" href="#sectionA">Section A</a></li>
<li><a data-toggle="tab" href="#sectionB">Section B</a></li>
<li><a data-toggle="tab" href="#sectionC">Section C</a></li>
</ul>
<div class="tab-content">
<div id="sectionA" class="tab-pane fade in active">
<h3>Section A</h3>
<p>Aliquip placeat salvia cillum iphone. Seitan aliquip quis cardigan american apparel, butcher voluptate nisi qui. Raw denim you probably haven't heard of them jean shorts Austin. Nesciunt tofu stumptown aliqua, retro synth master cleanse. Mustache cliche tempor, williamsburg carles vegan helvetica. Reprehenderit butcher retro keffiyeh dreamcatcher synth.</p>
</div>
<div id="sectionB" class="tab-pane fade">
<h3>Section B</h3>
<p>Vestibulum nec erat eu nulla rhoncus fringilla ut non neque. Vivamus nibh urna, ornare id gravida ut, mollis a magna. Aliquam porttitor condimentum nisi, eu viverra ipsum porta ut. Nam hendrerit bibendum turpis, sed molestie mi fermentum id. Aenean volutpat velit sem. Sed consequat ante in rutrum convallis. Nunc facilisis leo at faucibus adipiscing.</p>
</div>
<div id="sectionC" class="tab-pane fade">
<h3>Section C</h3>
<p>Vestibulum nec erat eu nulla rhoncus fringilla ut non neque. Vivamus nibh urna, ornare id gravida ut, mollis a magna. Aliquam porttitor condimentum nisi, eu viverra ipsum porta ut. Nam hendrerit bibendum turpis, sed molestie mi fermentum id. Aenean volutpat velit sem. Sed consequat ante in rutrum convallis. Nunc facilisis leo at faucibus adipiscing.</p>
</div>
</div>
</div>
부트스트랩과 다른 기본적인 것들을 부르는 것을 잊지 마세요.
다음은 빠른 코드입니다.
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
이제 설명을 시작하겠습니다.
위 예제의 jQuery 코드는 jQuery.attr() 메서드를 사용하여 새 탭이 표시될 때 요소의 href 특성 값을 가져오고 HTML5 localStorage 개체를 통해 사용자의 브라우저에 로컬로 저장합니다.나중에 사용자가 페이지를 새로 고치면 이 데이터를 검색하고 .tab('show') 메서드를 통해 관련 탭을 활성화합니다.
몇 가지 예를 찾아볼까요?여기 당신들을 위한 것입니다.https://jsfiddle.net/Wineson123/brseabdr/
제 대답이 여러분 모두에게 도움이 되었으면 좋겠습니다.치어리딩!:)
Xavi Martínez와 Koppor가 제공한 답변을 바탕으로 url 해시 또는 localStorage라는 이름을 사용하는 솔루션을 생각해 냈습니다.
function rememberTabSelection(tabPaneSelector, useHash) {
var key = 'selectedTabFor' + tabPaneSelector;
if(get(key))
$(tabPaneSelector).find('a[href=' + get(key) + ']').tab('show');
$(tabPaneSelector).on("click", 'a[data-toggle]', function(event) {
set(key, this.getAttribute('href'));
});
function get(key) {
return useHash ? location.hash: localStorage.getItem(key);
}
function set(key, value){
if(useHash)
location.hash = value;
else
localStorage.setItem(key, value);
}
}
용도:
$(document).ready(function () {
rememberTabSelection('#rowTab', !localStorage);
// Do Work...
});
사비 마르티네스 솔루션의 경우처럼 뒤로 버튼을 따라가지 못합니다.
내 코드는, 나에게 효과가 있고, 나는 사용합니다.localStorage
HTML5
$('#tabHistory a').click(function(e) {
e.preventDefault();
$(this).tab('show');
});
$("ul.nav-tabs#tabHistory > li > a").on("shown.bs.tab", function(e) {
var id = $(e.target).attr("href");
localStorage.setItem('selectedTab', id)
});
var selectedTab = localStorage.getItem('selectedTab');
$('#tabHistory a[href="' + selectedTab + '"]').tab('show');
제가 해봤는데 효과가 있어요.
jQuery(document).ready(function() {
jQuery('a[data-toggle="pill"]').on('show.bs.tab', function(e) {
localStorage.setItem('activeTab', jQuery(e.target).attr('href'));
});
// Here, save the index to which the tab corresponds. You can see it
// in the chrome dev tool.
var activeTab = localStorage.getItem('activeTab');
// In the console you will be shown the tab where you made the last
// click and the save to "activeTab". I leave the console for you to
// see. And when you refresh the browser, the last one where you
// clicked will be active.
console.log(activeTab);
if (activeTab) {
jQuery('a[href="' + activeTab + '"]').tab('show');
}
});
누군가에게 도움이 되길 바랍니다.
결과는 다음과 같습니다. https://jsfiddle.net/neilbannet/ego1ncr5/37/
아직 코멘트를 할 수 없기 때문에 위에서 답변을 베껴서 정말 도움이 되었습니다.하지만 나는 #id가 아닌 쿠키로 작업하기 위해 변경하여 변경사항을 공유하고자 했습니다.따라서 활성 탭을 한 번의 새로 고침(예: 다중 리디렉션)보다 더 오래 저장하거나 ID가 이미 사용되고 코퍼스 분할 방법을 구현하지 않으려는 경우에 저장할 수 있습니다.
<ul class="nav nav-tabs" id="myTab">
<li class="active"><a href="#home">Home</a></li>
<li><a href="#profile">Profile</a></li>
<li><a href="#messages">Messages</a></li>
<li><a href="#settings">Settings</a></li>
</ul>
<div class="tab-content">
<div class="tab-pane active" id="home">home</div>
<div class="tab-pane" id="profile">profile</div>
<div class="tab-pane" id="messages">messages</div>
<div class="tab-pane" id="settings">settings</div>
</div>
<script>
$('#myTab a').click(function (e) {
e.preventDefault();
$(this).tab('show');
});
// store the currently selected tab in the hash value
$("ul.nav-tabs > li > a").on("shown.bs.tab", function (e) {
var id = $(e.target).attr("href").substr(1);
$.cookie('activeTab', id);
});
// on load of the page: switch to the currently selected tab
var hash = $.cookie('activeTab');
if (hash != null) {
$('#myTab a[href="#' + hash + '"]').tab('show');
}
</script>
사비 마르티네스가 제공한 코드를 사용해 보았습니다.그것은 효과가 있었지만 IE7에서는 그렇지 않았습니다.문제는 탭이 관련 내용을 참조하지 않는다는 것입니다.
그래서 저는 그 문제를 해결하기 위해 이 코드를 선호합니다.
function pageLoad() {
$(document).ready(function() {
var tabCookieName = "ui-tabs-1"; //cookie name
var location = $.cookie(tabCookieName); //take tab's href
if (location) {
$('#Tabs a[href="' + location + '"]').tab('show'); //activate tab
}
$('#Tabs a').click(function(e) {
e.preventDefault()
$(this).tab('show')
})
//when content is alredy shown - event activate
$('#Tabs a').on('shown.bs.tab', function(e) {
location = e.target.hash; // take current href
$.cookie(tabCookieName, location, {
path: '/'
}); //write href in cookie
})
});
};
사비 마르티네스의 대답 외에도 클릭 시 점프를 피합니다.
점프 피하기
$(document).ready(function(){
// show active tab
if(location.hash) {
$('a[href=' + location.hash + ']').tab('show');
}
// set hash on click without jumb
$(document.body).on("click", "a[data-toggle]", function(e) {
e.preventDefault();
if(history.pushState) {
history.pushState(null, null, this.getAttribute("href"));
}
else {
location.hash = this.getAttribute("href");
}
$('a[href=' + location.hash + ']').tab('show');
return false;
});
});
// set hash on popstate
$(window).on('popstate', function() {
var anchor = location.hash || $("a[data-toggle=tab]").first().attr("href");
$('a[href=' + anchor + ']').tab('show');
});
중첩 탭
"_" 문자를 구분 기호로 사용한 구현
$(document).ready(function(){
// show active tab
if(location.hash) {
var tabs = location.hash.substring(1).split('_');
$.each(tabs,function(n){
$('a[href=#' + tabs[n] + ']').tab('show');
});
$('a[href=' + location.hash + ']').tab('show');
}
// set hash on click without jumb
$(document.body).on("click", "a[data-toggle]", function(e) {
e.preventDefault();
if(history.pushState) {
history.pushState(null, null, this.getAttribute("href"));
}
else {
location.hash = this.getAttribute("href");
}
var tabs = location.hash.substring(1).split('_');
//console.log(tabs);
$.each(tabs,function(n){
$('a[href=#' + tabs[n] + ']').tab('show');
});
$('a[href=' + location.hash + ']').tab('show');
return false;
});
});
// set hash on popstate
$(window).on('popstate', function() {
var anchor = location.hash || $("a[data-toggle=tab]").first().attr("href");
var tabs = anchor.substring(1).split('_');
$.each(tabs,function(n){
$('a[href=#' + tabs[n] + ']').tab('show');
});
$('a[href=' + anchor + ']').tab('show');
});
공유해 주셔서 감사합니다.
모든 해결책을 읽음으로써.저는 아래 코드로 url 해시 또는 localStorage라는 이름을 사용하는 솔루션을 생각해냈습니다.
$(function(){
$(document).on('shown.bs.tab', 'a[data-toggle="tab"]', function (e) {
localStorage.setItem('activeTab', $(e.target).attr('href'));
})
var hash = window.location.hash;
var activeTab = localStorage.getItem('activeTab');
if(hash){
$('#project-tabs a[href="' + hash + '"]').tab('show');
}else if (activeTab){
$('#project-tabs a[href="' + activeTab + '"]').tab('show');
}
});
페이지를 다시 로드하고 예상 탭을 선택한 상태로 유지하면 해결책이 있습니다.
데이터를 저장한 후 리디렉션된 URL이 my_url#tab_2라고 가정합니다.
이제 다음 스크립트를 통해 예상 탭이 선택된 상태로 유지됩니다.
$(document).ready(function(){
var url = document.location.toString();
if (url.match('#')) {
$('.nav-tabs a[href="#' + url.split('#')[1] + '"]').tab('show');
$('.nav-tabs a').removeClass('active');
}
});
부트스트랩 v4.3.1의 경우.아래를 시도해 보십시오.
$(document).ready(function() {
var pathname = window.location.pathname; //get the path of current page
$('.navbar-nav > li > a[href="'+pathname+'"]').parent().addClass('active');
})
html5를 사용하여 다음을 구성했습니다.
페이지 어딘가:
<h2 id="heading" data-activetab="@ViewBag.activetab">Some random text</h2>
뷰백에는 페이지/요소에 대한 ID만 포함되어야 합니다. 예:"스캐너덜너덜
site.js를 만들고 페이지에 스크립트를 추가했습니다.
/// <reference path="../jquery-2.1.0.js" />
$(document).ready(
function() {
var setactive = $("#heading").data("activetab");
var a = $('#' + setactive).addClass("active");
}
)
이제 당신이 해야 할 일은 당신의 아이디를 내비게이션 바에 추가하는 것입니다.예:
<ul class="nav navbar-nav">
<li **id="testing" **>
@Html.ActionLink("Lalala", "MyAction", "MyController")
</li>
</ul>
모두 데이터 속성을 환영합니다 :)
우리는 jquery 트리거를 사용하여 스크립트를 로드하여 버튼을 눌렀습니다.
$(.class_name").트리거("클릭");
이렇게 할 수 있는 방법은 아주 많습니다.제가 생각해 낸 것은 짧고 단순한 것입니다.
var url = document.location.toString();
if (url.match('#')) {
$('.nav-tabs a[href="#' + url.split('#')[1] + '"]').tab('show');
}
$('.nav-tabs a').on('shown.bs.tab', function (e) {
window.location.hash = e.target.hash;
if(e.target.hash == "#activity"){
$('.nano').nanoScroller();
}
})
에서setTab
함수 클래스 이름을 params 양식 탭으로 받아서 로컬 저장소에 저장했습니다.문서 준비 기능에서 활성 클래스가 있는지 확인했습니다. 있으면 해당 탭을 활성으로 설정하거나 기본 탭을 활성으로 설정합니다.
$(document).ready(function() {
var activeTab = localStorage.getItem('activeTab');
if (activeTab) {
$('#v-pills-'+activeTab+'-tab').addClass('active');
$('#v-pills-'+activeTab).addClass('show active');
} else {
$('#v-pills-basic-tab').addClass('active');
$('#v-pills-basic').addClass('show active');
}
})
function setTab(params) {
localStorage.setItem('activeTab', params);
}
언급URL : https://stackoverflow.com/questions/18999501/how-can-i-keep-selected-bootstrap-tab-on-page-refresh
'programing' 카테고리의 다른 글
-deloc가 아닌 -(void)viewDidUnload에서 개체를 언제 릴리스해야 합니까? (0) | 2023.07.31 |
---|---|
jQuery를 사용하여 리디렉션을 따르도록 Ajax 요청을 방지하는 방법 (0) | 2023.07.31 |
C float 비교 기능은 언제 사용합니까? (0) | 2023.07.31 |
PHP의 메모리 제한을 2GB 이상으로 늘리는 방법은 무엇입니까? (0) | 2023.07.31 |
구성 요소를 사용하지 않고 angular2 경로에서 외부 URL로 리디렉션하는 방법은 무엇입니까? (0) | 2023.07.31 |