js 无刷新评论模块

作者:root
oak_comment.js  文件

/* 评论 分页 类
* 使用说明:
* cfg = {
*	mod:'模块名',
*	pid:'被评文章所在分类ID',
*	cid:'被评文章ID',
*	inURL:'<?php echo libc_Filter::getInstance()->getURL('comment/write');?>',//添加 URL,需权限过滤
*	outURL:'<?php echo libc_Filter::getInstance()->getURL('comment/ls');?>',//读取 URL,需权限过滤
*	delURL:'<?php echo libc_Filter::getInstance()->getURL('comment/del');?>',//删除 URL,需权限过滤
*	rows:10,每页显示评论数
* };
* comment = new oak_comment(cfg);
* comment.render('.oak_comment');
*/
oak_comment = function(cfg){
	init= {
		method: "POST",
  		credentials: "include", 
  		cache: "no-cache"   
	};
};
oak_comment.prototype ={
	comment_node:null,
	edit_node:null,
	add_node :null,
	ul_node:null,
	pagesNode:null,
	Records:0,/*总评论记录数*/
	ten:10, /* 理论显示页数 */
	_tenNum: 0, /* 当前分页页 */
    _tenCount:0, /*分页页数*/
	_pagecount:0,/*页总数*/
    page:1, /*当前页*/
	_j: 0,/*实际显示页数*/
	li_html:'<div class="oak_comment_li"><div class="oak_comment_li_head"><span class="comment_user"></span>'+
		'<span class="comment_addtime"></span><span class="comment_del"></span></div><div class="comment_body"></div></div>',
	edit_html:'<div class="comment_edit"><div class="comment_edit_head"><span class="comment_edit_title"> 评: </span>'+
		'<span class="comment_edit_add">添加</span><div class="comment_edit_body" contenteditable="true"></div></div>',
	ajax:function(url,init,fn=null){
        fetch(url,init).then((response) => {return response.json();}).then((a) => {
            if(typeof fn =='function')fn(a);
		}).catch((e)=>{console.log('Fetch Error : ', e);});
    },
    add:function(a){ 
        if (a instanceof Object){
			if(a.records){this.Records = a.records;a=a.data;}
            var n = this._creat_li(a);
			this.ul_node.insertBefore(n,this.ul_node.firstChild);
			if(this.ul_node.childNodes.length > cfg.rows)
				this.ul_node.removeChild(this.ul_node.lastChild);
			this.InitPages();
        }
	},
    getFormData:function(){
		var fData = new FormData();
		for(k in cfg)fData.append(k,cfg[k]);
		return fData;
	},
	get:function(){	
		init.body = this.getFormData();
		init.body.append('page',this.page);
		this.ajax(cfg.outURL,init,(function(a) {
			this.Records = a.records;this.InitPages();
			this.ul_node.innerHTML='';
			for (i in a.data){
				n=this._creat_li(a.data[i]);
				this.ul_node.appendChild(n);
			}
		}).bind(this));
	},
	renderUI:function(){
		this.ul_node = document.createElement("div");
		this.ul_node.className = 'oak_comment_ul';
		this.edit_node=this.creatNode(this.edit_html);
		this.add_node = this.edit_node.querySelector('.comment_edit_add');
		this.comment_node.appendChild(this.ul_node);
		this.pagesNode = this.comment_node.appendChild(this.creatNode('<div class = comment_pages></div>'));
		if(cfg.inURL)this.comment_node.appendChild(this.edit_node);
	},
	_creat_li:function(a){
		var d,n=this.creatNode(this.li_html);
		n.querySelector('.comment_user').innerHTML='发布:'+a.USER;
		n.querySelector('.comment_addtime').innerHTML='日期:'+a.ADDTIME;
        n.querySelector('.comment_body').innerHTML=a.BODY.replace(/&lt;/g,'<').replace(/&gt;/g,'>');;
        d=n.querySelector('.comment_del');
        if(cfg.delURL){d.innerHTML=' 删除';d.setAttribute('name',a.ID)}
		return n;
	},
	bindUI:function(){
		this.add_node.addEventListener('click',(function(e){
			e.stopPropagation();
			var n= this.edit_node.querySelector('.comment_edit_body'),s=n.innerHTML;
            if (n.textContent.length > 0){
                if(cfg.char && s.length > cfg.char){alert('最多'+cfg.char+'个字符或汉字,你输入了:'+s.length);return;}
		        init.body = this.getFormData();
				init.body.append('body',s);
                this.ajax(cfg.inURL,init,this.add.bind(this));
                n.innerHTML='';
            }
        }).bind(this));
        this.ul_node.addEventListener('click',(function(e){
            e.stopPropagation();
            var id,n = e.target;
			if (id= e.target.getAttribute('name')){
				init.body = this.getFormData();
                init.body.append('id',id);
                this.ajax(cfg.delURL,init,(function(a){
					if(a==1){
						this.ul_node.removeChild(n.parentNode.parentNode);
						if((this.Records-1) % cfg.rows == 0 && this.page == this._pagecount){this.page--;}
						this.get();
					}
                }).bind(this));
            }
		}).bind(this));
		this.pagesNode.addEventListener('click',(function(e){
			e.stopPropagation();
			if(e.target.tagName!='A')return;
			var go = this.page,prev=this.pagesNode.querySelector('#page_'+go),fData = this.getFormData(),
				id = e.target.id, i = this._tenNum+1;
            switch (id){
				case 'prevpage':
                    go = this._tenNum * this.ten;
                    break;
				case 'nextpage':
                    go = i * this.ten+1;
                    break;
                case 'jumppage':
                    go = e.target.parentNode.querySelector('input').value;
                    break;
                default:
					go = id.split('_')[1];
            }
            if (go > this._pagecount || go < 1 || isNaN(go)) return;
			this.page = go;
			this.get();
		}).bind(this));
	},
	creatNode:function (s) { 
   	var n = document.createElement("div"); 
   	n.innerHTML = s; 
   	return n.childNodes[0]; 
	},
	render:function(s){
		this.comment_node=document.querySelector(s);
		this.renderUI();
		this.bindUI();
		this.get();
	},
	pagesUI: function(){
        this.pagesNode.innerHTML = '';
		if(this._pagecount>1){
			this.pagesNode.appendChild(this.creatNode('<span class="page_count">共 ' + this._pagecount + ' 页 </span>'));
			if(this.page > this.ten)
        		this.pagesNode.appendChild(this.creatNode('<span><a id="prevpage" class="prev_page"><<</a></span>'));
        	var i = 0,tmp = 0,cl;
        	while (i < this._j )
        	{
          		i++;
            	tmp = this.ten * this._tenNum + i;
				cl=(tmp == this.page)?'current_page':'';
            	this.pagesNode.appendChild(this.creatNode('<span class ="list_page '+cl+'"><a id="page_'+tmp+'">'+tmp+'</a><span>')); 
			}
			if(this._pagecount > this.ten && this._pagecount > (this._tenNum+1) * this.ten)
				this.pagesNode.appendChild(this.creatNode('<span><a id="nextpage" class="next_page" >>></a></span>'));
			if(this._pagecount > this.ten)
				this.pagesNode.appendChild(this.creatNode('<span class ="jump_page"> 第 <input type="text"> 页<a id ="jumppage" >GO</a></span>'));
		}
    },
	InitPages : function() {
        this._pagecount = Math.floor((this.Records - 1) / cfg.rows) + 1;
        this._tenNum    = Math.floor((this.page -1) / this.ten); 
        this._tenCount   = Math.floor(this._pagecount / this.ten); 
        if (this._pagecount < this.ten){ /* 如果总页数小于显示页数*/
            this._j = this._pagecount;
        }else if(this._tenNum >= this._tenCount){ /*如果当前页是最后页*/
            this._j = this._pagecount % this.ten ; 
        }else{
            this._j =this.ten;
        }
        this.pagesUI();
   	}
}

使用:

/* 评论js模块调用 */
cfg = {
	mod:'<?php echo $_GET['m']?>',
	pid:'<?php echo $this->res['0']['PID']?>',
	cid:'<?php echo $this->res['0']['ID']?>',
	inURL:'<?php echo libc_Filter::getInstance()->getURL('comment/write');?>',
	outURL:'<?php echo libc_Filter::getInstance()->getURL('comment/ls');?>',
	delURL:'<?php echo libc_Filter::getInstance()->getURL('comment/del');?>',
    rows:15,/*每页显示记录数*/
    char:1000,/* 限制提交字符数量 */
};
comment = new oak_comment(cfg);
comment.render('.oak_comment');

css 文件 

/* js分页 */
.num_page:hover {
	FONT-SIZE: 14px; LINE-HEIGHT: normal; FONT-FAMILY: Arial, Helvetica, sans-serif; BORDER: #ff9900 1px solid;
}
.comment_pages {HEIGHT:25;PADDING-TOP: 5px;color: #999;}
.comment_pages A {
      PADDING-RIGHT: 5px; PADDING-LEFT: 5px; TEXT-ALIGN: center;TEXT-DECORATION: none;
     FONT-WEIGHT: normal;MARGIN: 5px 2px; color: #999;
 }
.jump_page INPUT { width:25px;padding:2px;BORDER: #ccc 1px solid;}
.comment_edit_add,.comment_del,.prev_page,.next_page,.jump_page A{cursor: pointer;}
.list_page A {padding:3px 5px 3px 5px; BORDER: #ccc 1px solid;FONT-SIZE: 12px;cursor: pointer;}
.current_page A {color: #ff9900;}
.comment_edit,.oak_comment_li,.comment_pages,.comment_edit_body{MARGIN-TOP:5px;}
.comment_edit_body{padding:5px ;height:auto!important;min-height:80px;BORDER: #ccc 1px solid;outline:0px;}
.comment_del,.comment_edit_add{float:right;}
.comment_addtime{float:right;padding-left:50px;width: 100 px;}
.oak_comment_li_head{background:#eee;padding:5px 5px 5px 5px;color: #999;}
.comment_edit{color: #999;}