浏览器的返回/前进按钮用于在选项卡之间导航。

15

我收到了很多用户的投诉,他们使用我的基于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;
});

在相关的URL后面添加**#tab1#tab2**。 - Gerard
嗨@Gerard,我不太明白,请你能给个例子吗? - Efe
你应该意识到,阻止任何浏览器向后或向前导航可能会在未来被弃用,因为如果存在恶意脚本,它们可以并将控制您的浏览器,这正是大型浏览器开发人员不惜一切代价试图防止的原因。 - BRO_THOM
看一下jqueryUI Tabs插件:https://jqueryui.com/tabs/。此外,他们的文档也详细介绍了键盘导航。https://api.jqueryui.com/tabs/。看一下吧。 - Prasad Wargad
@Efe 你解决了吗? - Aabir Hussain
6个回答

13

我还没有测试你的代码,但我认为它会正确地导航,但无法保持活动选项卡(已选选项卡)? - Aabir Hussain

7

没有您的完整代码,我无法为您提供一个定制的示例,但您可以简单地向包含每个标签的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>

每次点击选项卡后,更新后的网址将如下所示: https://example.com#Tab1 https://example.com#Tab2 https://example.com#Tab3 https://example.com#Tab4

2
在一侧,您的下一个选项卡功能是用JavaScript编写的,在另一侧,浏览器中的返回按钮使用浏览器历史记录,因此这与您的功能无关,根本无法让您返回到上一个选项卡。
因此,您有两种方法可以实现:
1.尝试通过刷新浏览器在不同页面加载每个步骤,这样页面将保存在浏览器历史记录中,通过按返回按钮,您可以查看先前的步骤。
2.您应该有一个“上一页”按钮,就像您的“下一页”按钮一样,以查看上一个步骤。

2
实际上有一种方法,那就是浏览器中的历史记录API。它允许开发人员在应用程序中更新浏览历史记录,并且通常在单页应用程序中使用。https://developer.mozilla.org/en-US/docs/Web/API/History_API - ROOT

2

我使用了Bootstrap标签页和浏览器选项卡导航。下面是完整的示例:

<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> 点击“我的连接”


1
改变哈希值类似于推送状态 history.pushState,这会触发 popstate 事件。在浏览器上点击后退和前进按钮将弹出和推送这些状态,因此您不需要任何其他自定义处理程序。
PS:您可以从您的 active 类向 :target 添加 CSS 样式。这里的 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>


0

首先,您需要在点击事件中使用$event.preventDefault()来防止链接将URL提交到历史记录,并使用history.pushState(data, title, url)自定义历史记录。

在JavaScript中,我们有一个事件可以帮助我们控制用户的后退和前进事件。这个事件的名称是“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>


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接