我們從數據拿到消息想動態加載到html頁面,這要設計到ajax,這里ajax就不在重新敘述了,現在只講拿到數據后插入到頁面中,並且動態的生成底部的翻頁欄效果,用到jQuery庫。
主要思路是這個樣子的:
①拿到數據總的條數,根據每頁放多少個,來生成按鈕,切割數據。
首先老規矩,來個html代碼:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
<script src="jquery-1.11.3.min.js"></script>
<script src="index.js"></script>
<style type="text/css" media="screen">
.content{
height:250px !important;
}
li{
margin: 4px 4px;
}
.cur{
background-color: #7218EC;
}
</style>
</head>
<body>
<div>
<input type="button" name="" id="begin" value="begin" onclick="myGetDate(1000)">
<input type="button" name="" id="end" value="end">
</div>
//動態數據插入的地方
<ul id="content">
</ul>
//翻頁欄插入的地方
<ul id="pagesA">
</ul>
<ul id="nav">
<button type="" id="pageP">prev</button>
<button type="" id="pageN">next</button>
</ul>
</body>
</html>
這里是js代碼的地方inde.js:
function myGetDate(i){
var date = new Date();
var num=0;
var choiceBar = document.getElementById("pagesA");
var article = document.getElementById("content");
//動態的往ul里面插入數據,這個可以從數據庫里取出的數據,我本來想弄個時間戳的,功夫不到家,將就的看吧.
while(i){
$("#content").append("<li> Year : " + date.getFullYear() + " Month :" + date.getMonth() + " Day : " + date.getDate() + " hour : " + date.getHours() + " minute : " + date.getMinutes() + " second : " + i) + "</li>";
i--;
}
//動態的生成分頁按鈕的個數
var len = $("#content li").length;
for(var i=0; i<len/10; i++){
$("#pagesA").append("<li style='width:24px;height:24px;display:inline-block;border: 1px solid #D611EA;text-align:center;line-height:24px;'>" + (i+1) + "</li>");
}
$("#pagesA li:first-child").addClass("cur");
//給每個按鈕添加事件
for(var i=0; i<choiceBar.children.length; i++){
choiceBar.children[i].index = i;
choiceBar.children[i].onclick = function(){
for(var j=0; j<choiceBar.children.length; j++){
choiceBar.children[j].className = "";
}
this.className = "cur";
num = this.index;
init(num);
}
}
//上一個按鈕添加事件
$("#pageP").click(function(){
if(num==0){ //到第一頁的情況
return false;
}else{
for(var j=0; j<choiceBar.children.length; j++){
choiceBar.children[j].className = "";
}
choiceBar.children[num-1].className = "cur";
init(num-1);
return num--;
}
});
//下個按鈕添加事件
$("#pageN").click(function(){
if(num==choiceBar.children.length-1){ //到最后一頁的情況
return false;
}else{
for(var j=0; j<choiceBar.children.length; j++){
choiceBar.children[j].className = "";
}
choiceBar.children[num+1].className = "cur";
init(num+1);
return num++;
}
});
//顯示與按鈕對應的十個信息
function init(myNum){
for(var j=0; j<choiceBar.children.length; j++){
for(var i=0; i<10; i++){
if(article.children[(j*10)+i] == undefined){
continue;
}
article.children[(j*10)+i].style.display = "none";
}
}
for(var i=0; i<10; i++){
if(article.children[(myBum*10)+i] == undefined){
continue;
}
article.children[(myBum*10)+i].style.display = "block";
}
}
init(0);
}
