简体   繁体   English

使用后退和下一个按钮在html页面之间切换

[英]Switching between html pages using a back and next button

This is my website http://www.damianplisko.com I want to have a previous and next button which switches between my html portfolio pages.If the user is on one of my porftfolio pages, all they have to do is click next and it takes them to the next portfolio page instead of maneuvering back to the main menu. 这是我的网站http://www.damianplisko.com我想有一个上一个和下一个按钮,在我的html投资组合页面之间切换。如果用户在我的一个porftfolio页面上,他们所要做的就是点击下一步它将它们带到下一个投资组合页面而不是回到主菜单。 Anyway to do this using js? 无论如何使用js做到这一点?

Since you're not using a CMS (which I recommend) the easiest solution I can think of without using AJAX or any external libraries is to create an array with all your pages in the order you want them displayed. 由于您没有使用CMS(我推荐),因此我可以在不使用AJAX或任何外部库的情况下考虑最简单的解决方案,即按照您希望显示的顺序创建一个包含所有页面的数组。

var pages = [
  'MedTech.html',
  'Trainer.html',
  'YoungGuns.html',
  ...
];

Then you can set the your new URL by grabbing the current page and checking which one is next. 然后,您可以通过抓取当前页面并检查下一页是否设置新URL。

var next = document.getElementById('next'); // your DOM element

next.addEventListener('click', function() {

  var current = location.pathname, // current page ie. MedTech.html
      idx = pages.indexOf( current ); // find page in pages array

  // go to next page if page exists
  // otherwise go to first page   
  if ( idx > -1 ) {
    location.pathname = pages[ ++idx ] || pages[0];
  }

});

For a "back" button you could simply use the history or adjust the function above. 对于“后退”按钮,您只需使用历史记录或调整上述功能即可。

Edit: you could get away without the idx > -1 check if you make sure all the pages in the array exist for sure. 编辑:你可以在没有idx > -1情况下离开,检查是否确保数组中的所有页面都存在。

Another way to do this with jquery is: 使用jquery执行此操作的另一种方法是:

    var pages = ['page1.html', 'page2.html', 'page3.html'];

    $(".nav-button").on('click', function () {
        var currentPage = location.pathname,
            idx = pages.indexOf(currentPage),
            newIndex, failOver;
        if (idx > -1) {
            newIndex = $(this).hasClass("next") ? ++idx : --idx;
            failOver = $(this).hasClass("next") ? 0 : 2;
            location.pathname = pages[newIndex] || pages[failOver];
        }
    });

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM