mui分页控件数据绑定封装

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/qq_28254093/article/details/81122000

1.效果图

 2.调用HTML和js        list-news-notice.html

<!DOCTYPE html>
 <html>
    
	<head>
		<meta charset="utf-8">
		<title>Hello MUI</title>
		<meta name="viewport" content="width=device-width, initial-scale=1,maximum-scale=1,user-scalable=no">
		<meta name="apple-mobile-web-app-capable" content="yes">
		<meta name="apple-mobile-web-app-status-bar-style" content="black">

		<!--标准mui.css-->
		<link rel="stylesheet" href="../css/mui.min.css">
		<!--App自定义的css-->
		<link rel="stylesheet" type="text/css" href="../css/app.css"/>
		<link href="../css/mui.picker.css" rel="stylesheet" />
		<link href="../css/mui.poppicker.css" rel="stylesheet" />
		<style>
			.mui-table h4,.mui-table h5,.mui-table .mui-h5,.mui-table .mui-h6,.mui-table p{
		        margin-top: 0;
		    }
		    .mui-table h4{
		        line-height: 21px;
		        font-weight: 500;
		    }
		
		    .mui-table .oa-icon{
		        position: absolute;
		        right:0;
		        bottom: 0;
		    }
		    .mui-table .oa-icon-star-filled{
		        color:#f14e41;
		    }
		</style>
	</head>

	<body>
		<header class="mui-bar mui-bar-nav">
		    <a class="mui-icon mui-icon-left-nav mui-pull-left" ></a>
		    <h1 class="mui-title">通知公告</h1>
		</header>
		<div class="mui-content">
		    <div>
			    <ul id="nowList" class="mui-table-view mui-table-view-striped mui-table-view-condensed" style="display:none;">
			        <li class="mui-table-view-cell" id="{NewsId}" style="margin: 5px auto;">
			            <div class="mui-table">
			                <div class="mui-table-cell mui-col-xs-10">
			                    <h4 class="mui-ellipsis">{FullHead}</h4>
			                    <h5>作者:{AuthorName} &nbsp;&nbsp;小编:{CompileName}</h5>
			                   
			                </div>
			                <div class="mui-table-cell mui-col-xs-3 mui-text-right">
			                    <span class="mui-h5">{ReleaseTime}</span>
			                </div>
			            </div>
			        </li>
			    </ul>
			    <div style="height: 45px;width: 100%;"></div>
		  </div>
		</div>
	</body>
	<script src="../js/mui.min.js"></script>		
	<script src="../js/mui.picker.js"></script>
	<script src="../js/mui.poppicker.js"></script>
	<script src="../libs/mui.pagination.js"></script>
	
	<script>
		mui.init({
			swipeBack:true //启用右滑关闭功能
		});
		
		var editor=request("editor");
		console.log(editor);
		document.getElementsByClassName("mui-title")[0].innerText=editor=="news"?"最近新闻":"通知公告";
		var serverData=editor=="news"?getNewList():getNoticeList();
		
		
		cratePagination(loadData=function (_page){
			_page=parseInt(_page)||1;
			serverData.postData["pages"]=_page;
			mui.ajax(serverData.url,{
				data:serverData.postData,
				dataType:'json',//服务器返回json格式数据
				type:'get',//HTTP请求类型
				timeout:10000,//超时时间设置为10秒;
				success:function(data){
					var total=parseInt(data["total"]);
					var page=parseInt(data["page"]);
					document.getElementsByClassName("mui-pagination")[0].style["display"]=total>0?"block":"none";
					document.getElementsByClassName("mui-table-view")[0].style["display"]=total>0?"block":"none";
					document.getElementById("last").setAttribute("page-val",total);
					bandData(data["rows"]);
					setNowPageTotal(page,total);

				},
				error:function(xhr,type,errorThrown){
					console.log(JSON.stringify(xhr));
					console.log(JSON.stringify(errorThrown));
					console.log(JSON.stringify(type));
				}
			});
		});
		loadData();
		function bandData(data){
			var json=[];
			for(var i=0;i<data.length;i++){
				delete data[i].NewsContent;
				json.push(data[i]);
			}
			bandTempList(json,"nowList",true,true);
			document.getElementById("nowList").style["display"]=json.length>0?"block":"none";
		}
		
		mui('.mui-bar-nav').on('tap','a',function(){
			plus.webview.currentWebview().close();
		});
	</script>
</html>

3.分页js文件,目前比较粗糙,mui.pagination.js

function cratePagination(loadPageData){
	//1.创建 pagination
	document.getElementsByTagName("body")[0].innerHTML+=paginHtmlTemp();
	//2.注册事件
		//添加分页事件
		mui('.mui-pagination').on('tap','li',function(){
			var _id=this.getAttribute("id");
			if(_id=="showUserPicker"){
				return;
			}
			var _t=getNowPageTotal();
			var news=_t["page"];
			var last=_t['total'];
			
		   	var pageVal={"first":1,last:last,"prev":(news-1<=0?1:news-1),"next":(news+1>=last?last:news+1)};
		   	_page=pageVal[_id];

		   	document.getElementById("showUserPicker").setAttribute('page-val',_page);
		   	//调用数据方法
		   	if(typeof loadPageData =="function"){
				loadPageData(_page);
				//注册页数下拉时间
				InitSelectPage(loadPageData);
			}
		   	//处理按钮显示还是禁用
		   	var dis = function(id,isDisplay) {
				var f=document.getElementById(id);
				var className=f.getAttribute("class");
				var className=isDisplay==true?className+("mui-disabled "):className.replace("mui-disabled","");
				f.setAttribute("class",className);
			};

			dis('first',_page==1);
			dis('last',_page==last);
		}) 
	
	
	
}


var userPicker ;
function InitSelectPage(loadPageData){
	var _t=getNowPageTotal();
	var page=_t["page"];
	var total=_t['total'];
	userPicker=userPicker|| new mui.PopPicker()
	total=parseInt(total);
	var data=[];
	for(var i=0;i<total;i++){
		data.push({text:(i+1)+'/'+total,value:(i+1)});
	}		

	userPicker.setData(data);
	
	var showUserPickerButton = document.getElementById('showUserPicker');
	var userResult = document.getElementById('userResult');
	userResult.innerText = page+"/"+total;
	showUserPickerButton.addEventListener('tap', function(event) {
		userPicker.show(function(items) {					
			userResult.innerText = items[0]["text"];

			//返回 false 可以阻止选择框的关闭
			showUserPickerButton.setAttribute("page-val",items[0]["value"]);
			loadPageData(items[0]["value"]);
			
			//return false;
		});
	}, false);	
	
}

//设置当前页和总页数
function setNowPageTotal(page,total){
	var html='<a href="#" id="userResult">'+page+"/"+total+" </a>";
	document.getElementById("userResult").innerHTML=html;
	return html;
}

//得到当前页和总页数
function getNowPageTotal(){
	var _val=document.getElementById("showUserPicker").innerText.replace(/[^0-9/]*/g,"");
	_val=_val==""||_val.indexOf("undefined")>=0||_val.indexOf("null")>=0?[1,1]:_val.split("/");
	var page=_val[0];
	var total=_val[1];
	return {page:parseInt(page),total:parseInt(total)};
}


function paginHtmlTemp(){
	return 	'<div  style="bottom: 0px;position: fixed;background-color: #fdfdfd;width: 100%;padding: 2px;">'+
			'	<ul class="mui-pagination " style="display: block">'+
			'		<li class="mui-previous" id="first"  page-val="1"><a href="#" >首页</a></li>'+
			'		<li  class="mui-previous" id="prev"><a href="#">上一页</a></li>'+
			'		<li id="showUserPicker" page-val="1"><a href="#" id="userResult"> 1/1 </a> </li>'+
			'       <li class="mui-next"  id="next"><a href="#" >下一页</a></li>'+
			'		<li class="mui-next" id="last"><a href="#" >尾页	</a></li>'+
			'	</ul>'+
			'</div>';
	
}

4.涉及到的方法

//缓存要操作模板
var tempCache = {};
/**
 * 绑定数据到 块
 * @param {} json  后台json数据
 * @param {} trName 前台模板tr id
 * @param {} isRplace 是否处理特殊字符 
 * @returns {} object
 */
function bandTempList(json, id,isRplace) {
	isRplace=isRplace==undefined?true:false;

    var data = document.getElementById(id);
    var cacheHtmls = tempCache[id] =tempCache[id] || data.innerHTML.replace(/[\r\t\n]/g, " ");
    var tbodyHtml = "";
//  console.log(cacheHtmls);
    for (var i = 0; i < json.length; i++) {
        var innerHtmls = cacheHtmls;
        for (var _json in json[i]) {
            var value =json[i][_json];
            value=value||'未知';
            var regex = new RegExp("[{]" + _json + "[}]", "g");
            innerHtmls = innerHtmls.replace(regex, value);
        }
        tbodyHtml +=isRplace==true? innerHtmls.replace(/[{][a-zA-Z0-9]*[}]/g,""):innerHtmls;
    }
    data.innerHTML = tbodyHtml;
    return tbodyHtml;
}




/**
 * 得到地址栏参数
 * @param {Object} key 键
 * @param {Object} isDecodeURI  是否解码
 */
function request(key,isDecodeURI,url) {
	url=url|| window.location.href;
	if(url.indexOf("?")<0){
		return undefined;
	}
	isDecodeURI=isDecodeURI||false;
	var _request =url;
	(isDecodeURI==true)&&(_request=decodeURI(_request));
	_request = "{'"+_request.replace(/[']|["]/g,"").replace(/.*[?]/, "").replace(/&/g, "','").replace(/=/g, "':'") +"'}";
    
    _request = eval("(" + _request + ")");
    return key == undefined||key == null ? _request : _request[key];
}


/**
 * 得到新闻
 */
function getNewList(){
	return {
		url:数据接口,
		postData:{
			pages: 1,
			rows:6
		}
	}
}

/**
 * 得到通告
 */
function getNoticeList(){
	return {
		url:数据接口,
		postData:{
			pages: 1,
			rows:6
		}
	}
}

5.请求获取的数据格式

{
	"rows": [{
		"NewsId": "cf3bd612-cd7f-42b3-91e7-a7777bb0ea2b",
		"TypeId": 1,
		"ParentId": null,
		"Category": "国内新闻",
		"FullHead": "关于进一步规范村卫生室、个体诊所静脉输液管理工作的通知",
		"FullHeadColor": null,
		"BriefHead": null,
		"AuthorName": "45454545",
		"CompileName": "3453",
		"TagWord": "3453",
		"Keyword": "345345",
		"SourceName": null,
		"SourceAddress": null,
		"NewsContent": "",
		"PV": 0,
		"ReleaseTime": "2018-06-11 19:03:25",
		"SortCode": null,
		"DeleteMark": 0,
		"EnabledMark": 1,
		"Description": null,
		"CreateDate": "2018-06-11 19:03:25",
		"CreateUserId": "System",
		"CreateUserName": "超级管理员",
		"ModifyDate": "2018-06-11 19:03:25",
		"ModifyUserId": null,
		"ModifyUserName": null
	},{
		"NewsId": "cf3bd612-cd7f-42b3-sdwe7-a7777bb0ea2b",
		"TypeId": 1,
		"ParentId": null,
		"Category": "国内新闻",
		"FullHead": "关于进一步规范村卫生室、个体诊所静脉输液管理工作的通知",
		"FullHeadColor": null,
		"BriefHead": null,
		"AuthorName": "45454545",
		"CompileName": "3453",
		"TagWord": "3453",
		"Keyword": "345345",
		"SourceName": null,
		"SourceAddress": null,
		"NewsContent": "",
		"PV": 0,
		"ReleaseTime": "2018-06-11 19:03:25",
		"SortCode": null,
		"DeleteMark": 0,
		"EnabledMark": 1,
		"Description": null,
		"CreateDate": "2018-06-11 19:03:25",
		"CreateUserId": "System",
		"CreateUserName": "超级管理员",
		"ModifyDate": "2018-06-11 19:03:25",
		"ModifyUserId": null,
		"ModifyUserName": null
	},{
		"NewsId": "cf3bd612-cd7f-42b3-dwef-a7777bb0ea2b",
		"TypeId": 1,
		"ParentId": null,
		"Category": "国内新闻",
		"FullHead": "关于进一步规范村卫生室、个体诊所静脉输液管理工作的通知",
		"FullHeadColor": null,
		"BriefHead": null,
		"AuthorName": "45454545",
		"CompileName": "3453",
		"TagWord": "3453",
		"Keyword": "345345",
		"SourceName": null,
		"SourceAddress": null,
		"NewsContent": "",
		"PV": 0,
		"ReleaseTime": "2018-06-11 19:03:25",
		"SortCode": null,
		"DeleteMark": 0,
		"EnabledMark": 1,
		"Description": null,
		"CreateDate": "2018-06-11 19:03:25",
		"CreateUserId": "System",
		"CreateUserName": "超级管理员",
		"ModifyDate": "2018-06-11 19:03:25",
		"ModifyUserId": null,
		"ModifyUserName": null
	}],
	"total": 3,
	"page": 1,
	"records": 13,
	"costtime": "8"
}

猜你喜欢

转载自blog.csdn.net/qq_28254093/article/details/81122000
今日推荐