使用按钮循环显示html文件列表

时间:2013-02-21 20:53:42

标签: javascript html cycle

我有一份产品清单说:

laptops/prod1.html
laptops/prod2.html
laptops/prod3.html
monitors/prod1.html
monitors/prod2.html
monitors/prod3.html

我想在我的页面上设置一个“循环”可用项目的按钮。

不知道该怎么做。这可以用javascript吗?

2 个答案:

答案 0 :(得分:0)

function nextProduct(incr) {
  var href = window.location.href
    , offset = (typeof(incr)==='undefined' ? 1 : incr);
  window.location = href.replace(/(\d+)\.html/, function(m, g1) {
    return (Number(g1) + offset) + '.html'
  });
}

然后你可以做类似的事情:

var button;
button = document.getElementByID('next-button');
button.addEventListener('click', function() { nextProduct(1); });
button = document.getElementByID('prev-button');
button.addEventListener('click', function() { nextProduct(-1); });

答案 1 :(得分:0)

设置一个主页面,这不应该是一个静态的html页面,而是用你选择的服务器端语言。

使用脚本标记将jquery包含到主页面(您可以从http://jquery.com/获取jquery)。

您的HTML可能如下所示:

<div id='content'></div>
<div>
   <a href='javascript:void(0)' id='prev' class='btn'>Previous</a>
   <a href='javascript:void(0)' id='next' class='btn'>Next</a>
</div>

在你的js文件中你会有这样的东西:

var currPage = 0;
var pageList = ["laptops/prod1.html","laptops/prod2.html", "laptops/prod3.html"];
var totalPages = pageList.length;
$(".btn").on("click",function(){
   //if we are at the last page set currpage = 0 else increment currPage.
   currPage = currPage < (totalPages - 1) ? ++currPage : 0;
   var page = pageList[currPage];
   $('#content').load(currPage);
});

需要考虑的一些要点:

  1. 您需要决定是否在主页加载或点击
  2. 上加载第一页
  3. 您需要设置一个js变量来跟踪当前加载的页面
  4. 您需要添加一些存储所有可能页面的方法(想想一个数组)。这可以打印到页面加载页面上的脚本标记。
  5. 你需要决定当你到达终点时会发生什么。您可以循环或灰显适当的链接。
  6. jquery on jquery load