根据另一个对象键/值

时间:2016-01-29 16:42:55

标签: javascript jquery html jsobject

我的网站看起来像一本书,第一页是上一页的下一页。可以把它想象成书中的前后翻页。它不是浏览器中的上一页,它在页面内部。就像你正在改变书中的页面一样

我正在尝试动态分配上一页和下一页按钮的链接。目前,页面位于Object中,其中pageNum和fileName为键

我正在尝试根据当前页面链接的页码设置上一个链接。请参阅下面的示例和代码。



var toc = [
    {"pageNum": "1", "fileName": "index.html"},
    {"pageNum": "2", "fileName": "about.html"},
    {"pageNum": "3", "fileName": "work.html"},
    {"pageNum": "4", "fileName": "blog.html"},
    {"pageNum": "5", "fileName": "contact.html"},
  ];
  
var url = window.location.pathname;
var currentPage = url.substring(url.lastIndexOf('/')+1);
  
var prevPageNum;
var prevPage;
  
//Based on currentPage, find object entry in toc and apply related pageNum
toc.filter(function(toc){
  if(toc.fileName == currentPage) {
    $('#currentPageNumber').append(toc.pageNum);
  }
});
  
  /******* Last and Next Page Assignment *******/

toc.filter(function(toc){
  if(toc.fileName == currentPage) {
    prevPageNum = toc.pageNum-1;
    prevPage = toc.fileName;
  
    $('#prevPage').append(prevPage);
    //final code
    //$('#prevPage').attr("href",prevPage);
  }
});

<a href="#" id="prevPage">Previous Page</a>
<a href="#" id="nextPage">Next Page</a>
&#13;
&#13;
&#13;

实施例

currentPage about.html prevPage需要 index.html

2 个答案:

答案 0 :(得分:0)

如何在点击处理程序中导航到新网址:

$('#prevPage').click(function() {
    window.location.href = prevPage;
});

答案 1 :(得分:0)

对我来说,看起来你想创建一个single page web application,并且有很多框架值得使用。

要回答实际问题,也许您可​​以在一个页面中加载所有元素,并隐藏 - 取消隐藏它们。

$( document ).ready(function(){
	$(".content").css("display","none");
	var currentPage = 1;
        $("#block" + currentPage).css("display","block");
	$("#prev").click(function(){
		$(".content").css("display","none");
		currentPage--;
        if(currentPage == 0) currentPage = 2;
		$("#block" + currentPage).css("display","block");
	});
	$("#next").click(function(){
		$(".content").css("display","none");
		currentPage++;
        if(currentPage == 3) currentPage = 1;
		$("#block" + currentPage).css("display","block");
	});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<a href = "#" id = "prev"> Previus</a>
<a href = "#" id = "next"> Next</a>
<div id = "block1" class = "content">
This is home page
</div>
<div id = "block2" class = "content">
This is about page
</div>