사용자가 jQuery 기반 탭을 사용할 때 브라우저에서 다시 방문하면 이전 탭으로 이동하지 않고 이전 페이지로 이동한다는 성가신 사용자로부터 불만을 많이 받고 있습니다. . 다음 이전 / 다음 버튼을 추가했지만 충분하지 않습니다. 사용자가 브라우저 뒤로 화살표를 클릭 할 때 이전 페이지가 아닌 이전 탭으로 이동하도록 단추를 재구성하는 방법 여기서 테스트 할 수 있습니다 .
$('#quicktabs-registration_steps').append('<div class="prevnext"><a class="tablink-prev btn" href="#">Prev</a><a class="tablink-next btn btn-lg btn-primary" href="#">Continue</a></div>');
$('.tablink-prev').click(function () {
var index = $('.quicktabs-tabs li.active').index();
$('.quicktabs-tabs li').eq(index).removeClass('active');
if (index == 0) {
index = 1;
}
$('.quicktabs-tabs li').eq(index - 1).addClass('active');
$('.quicktabs-tabs li').eq(index - 1).find('a').click();
return false;
});
$('.tablink-next').click(function () {
var length = $('.quicktabs-tabs').first().children().size();;
var index = $('.quicktabs-tabs li.active').index();
$('.quicktabs-tabs li').eq(index).removeClass('active');
// if (parseInt(index) == parseInt(length) - 1 ) {
// index = index - 1;
// }
if (parseInt(index) == parseInt(length) - 1) {
window.location.href = '/home'; //redirect to home
//index = index - 1;
}
$('.quicktabs-tabs li').eq(index + 1).addClass('active');
$('.quicktabs-tabs li').eq(index + 1).find('a').click();
return false;
});
답변
히스토리를 사용할 수 있습니다.
새 탭이 열리면 히스토리 상태 푸시
history.pushState({page: 1}, "title 1", "?page=1")
참조 :
https://developer.mozilla.org/en-US/docs/Web/API/History_API
답변
전체 코드가 없으면 맞춤형 예제를 제공 할 수 없지만 div가 포함 된 각 탭에 앵커 태그를 추가 할 수 있습니다.
사용자가 탭 링크를 클릭 할 때마다 URL이 업데이트됩니다. 이러한 URL 변경 사항은 브라우저 기록에 저장되며 뒤로 탐색 할 때 다시 호출됩니다.
<div id="Tab1">
<h2><a href="#Tab1">Tab 1</a></h2>
<p>This tab content</p>
</div>
<div id="Tab2">
<h2><a href="#Tab2">Tab 2</a></h2>
<p>This tab content</p>
</div>
<div id="Tab3">
<h2><a href="#Tab3">Tab 3</a></h2>
<p>This tab content</p>
</div>
<div id="Tab4">
<h2><a href="#Tab4">Tab 4</a></h2>
<p>This tab content</p>
</div>
탭을 클릭 할 때마다 업데이트 된 URL은 다음과 같습니다.
https://example.com#Tab1
https://example.com#Tab2
https://example.com#Tab3
https://example.com#Tab4
답변
한쪽에서 다음 탭 기능은 자바 스크립트로 작성되고 다른 쪽에서 브라우저의 뒤로 버튼은 브라우저 기록을 사용하므로 기능과 관련이 없으며 이전 탭으로 이동할 수 없습니다.
따라서 두 가지 방법으로이를 수행 할 수 있습니다.
첫 번째 : 브라우저를 새로 고쳐서 각 페이지를 다른 페이지에로드하려고하면 페이지가 브라우저 기록에 저장되고 뒤로 버튼을 누르면 이전 단계를 볼 수 있습니다
2 단계 : 다음 단계 단추와 마찬가지로 이전 단계를 보려면 “이전”단추가 있어야합니다.
답변
아래의 브라우저 탭 탐색과 함께 부트 랩 탭을 사용했습니다.
<div class="tabs-Nav border-top-0">
<ul class="nav" role="tablist">
<li>
<a
id="friends"
data-pagination-id="friends"
class="active"
data-toggle="tab"
href="#friendsTab"
role="tab"
aria-controls="friends"
aria-selected="true">
Friends
</a>
</li>
<li>
<a id="followers" data-pagination-id="followers" class="" data-toggle="tab" href="#followersTab" role="tab" aria-controls="followers" aria-selected="false">
Followers
</a>
</li>
<li>
<a id="followings" data-pagination-id="followings" class="" data-toggle="tab" href="#followingTab" role="tab" aria-controls="followings" aria-selected="false">
Following
</a>
</li>
<li>
<a id="invites" data-pagination-id="invites" class="" data-toggle="tab" href="#invitesTab" role="tab" aria-controls="invites" aria-selected="false">
Invites
</a>
</li>
</ul>
</div>
/**
* add // id="friends" data-pagination-id="friends"
* in your html tabs the demo html is also added.
**/
$(document).ready(function () {
const param = 'tabID';
$("[data-pagination-id]").click(function () {
const pageParam = $(this).attr('data-pagination-param') || param;
//add tabId to the params
addParam(pageParam, $(this).attr('data-pagination-id'), true);
});
const preTab = getParamVal(param);
if (param) {
$('[data-pagination-id="'+ preTab +'"]').click();
}
});
/**
* add params to the url if preParams is false then all previous
* params will be removed.
**/
addParam = (pageParam, paramValue, preParams) => {
//get current url without params
var mainUrl = window.location.href.split('?')[0];
//get params without url
var paramString = location.search.substring(1);
if (preParams && paramString) { //when params found
//change param string to json object
var paramsObj = JSON.parse('{"' + decodeURI(paramString).replace(/"/g, '\\"').replace(/&/g, '","').replace(/=/g, '":"') + '"}');
} else {
//when current params are empty then create an empty object.
var paramsObj = {};
}
//only for ads tabs
if (pageParam) {
//add tabId to the params
paramsObj[pageParam] = paramValue;
//push params without refreshing the page.
history.pushState(false, false, mainUrl + '?' + $.param(paramsObj).replace(new RegExp('%2B', 'gi'), '+'));
}
};
/**
* Get value of a params from url if not exists then return null
**/
getParamVal = (pageParam) => {
const mainUrl = window.location.href.split('?')[0];
const paramString = location.search.substring(1);
const paramsObj = JSON.parse('{"' + decodeURI(paramString).replace(/"/g, '\\"').replace(/&/g, '","').replace(/=/g, '":"') + '"}');
return paramsObj[pageParam];
};
내 코드의 실제 작동 예를 확인할 수 있습니다
1> https://www.notesgen.com으로 이동 (데스크톱 사용)
2> 학생으로 계정을 만듭니다
3> 내 계정으로 이동 / 내 다운로드
4> 내 연결을 클릭하십시오
답변
해시 변경은 이벤트 history.pushState
를 트리거 하는 푸시 상태와 유사합니다 popstate
. 브라우저에서 앞뒤로 치는 것은 이러한 상태를 팝업하고 푸시하므로 다른 사용자 지정 처리기가 필요하지 않습니다.
추신 : 수업 :target
에서 CSS 스타일을 추가 할 수 있습니다 active
. window.addEventListener('popstate'
여기에 단지 로그는 당신에게 이벤트를 보여하지만은 event.state
항상이 경우 null이됩니다.
코드 스 니펫을 실행 하여 탭을 탐색 한 다음 브라우저의 뒤로 및 앞으로 버튼을 사용하십시오.
<style type="text/css">
div { display: none }
:target { display: block }
</style>
<h2><a href="#Tab1">Tab 1</a> | <a href="#Tab2">Tab 2</a> | <a href="#Tab3">Tab 3</a> | <a href="#Tab4">Tab 4</a></h2>
<div id="Tab1">
<p>This tab 1 content</p>
</div>
<div id="Tab2">
<p>This tab 2 content</p>
</div>
<div id="Tab3">
<p>This tab 3 content</p>
</div>
<div id="Tab4">
<p>This tab 4 content</p>
</div>
<script>
(() => {
history.pushState(null, '', '#Tab1');
window.addEventListener('popstate', event => {
console.log(window.location.hash);
});
})()
</script>
답변
첫 번째로 필요한 것은 클릭 이벤트에서 $ event.preventDefualt () 로 히스토리에서 URL을 제출하는 링크를 방지하고 history.pushState (data, title, url)로 히스토리를 사용자 정의하십시오 .
js에는 사용자가 뒤로 및 앞으로 이벤트를 제어하는 데 도움이되는 이벤트가 있습니다. 이 이벤트 이름은 “popstate”입니다. window.addEventListener ( ‘popstate’, callback)에서 사용할 수 있습니다 . 콜백 기능에서 탭을 활성화 및 비활성화하고 (클래스 추가 및 제거) URL을 추출 할 수 있습니다.
샘플 코드로 이것을 보여줍니다. 더 잘하고 이해하기 위해서는 여기에서 URL을 변경하는 것이 제한되어 있으므로 서버 또는 로컬 서버에서 시도하십시오.
$('nav ul a').on('click', function($e) {
function appendContent(hash) {
$('#content').text(`Content of item ${hash} `);
}
$e.preventDefault(); // when click the link stay in page
let _this = this; // get the link tag
let hash = _this.hash.replace(/\#/, '');
appendContent(hash);
$('li').removeAttr('class');
$('a').removeAttr('class');
$(`a[href*=${hash}]`).addClass('text-white').addClass('border-0').parent().addClass('bg-primary').addClass('last-style');
history.pushState('', _this.text, hash); // add the link in history
window.addEventListener('popstate', function ($e) {
let hashAgain = location.hash.replace(/\#/, ''); // you extract the hash
appendContent(hashAgain); // set the content of the back or forward link
$('li').removeAttr('class');
$('a').removeAttr('class');
$(`a[href*=${hash}]`).addClass('text-white').addClass('border-0').parent().addClass('bg-primary').addClass('last-style'); // update the status of tab
});
});
ul li {
display: inline-block;
margin: 1em;
}
li a,
.last-style {
border: 1px solid;
padding: 0.5em 1em;
}
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8" >
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Learning Java Script In Deep</title>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css">
<script type="text/javascript" src="js/angular/angular.min.js"></script>
</head>
<body>
<header class="text-center text-black-50">
<h1>Learning JS in Deep</h1>
<nav id="">
<ul id="">
<li><a href="#home" class="home">Home</a></li>
<li><a href="#item1">Item 1</a></li>
<li><a href="#item2">Item 2</a></li>
<li><a href="#item3">Item 3</a></li>
<li><a href="#item4">Item 4</a></li>
</ul>
</nav>
</header>
<div class="container m-auto text-center" id="content">
<p>Load <em class="text-danger">Content</em> in Here</p>
</div>
<script
src="https://code.jquery.com/jquery-3.4.1.js"
integrity="sha256-WpOohJOqMqqyKL9FccASB9O0KwACQJpFTUBLTYOVvVU="
crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.16.0/umd/popper.min.js"></script>
<!-- Latest compiled JavaScript -->
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.4.1/js/bootstrap.min.js"></script>
</body>
</html>
답변
