仿网易评论盖楼 JS 实现 | html

#编程技术 2020-09-15 13:32:09 | 全文 614 字,阅读约需 2 分钟 | 加载中... 次浏览

👋 相关阅读


看了些评论引用盖楼的网站,觉得网易的效果比较好,简单明了,让人看了就知道是引用评论,迟点准备自己也写个玩玩,应该能从中学到不少东西. 前端部分实现如下:https://www.phpvar.com/archives/1382.html

JS部分实现如下:

<div class="comments">
        <div></div>
        <div class="coms_head">评论列表</div>
        <div class="coms_body" id="commentArea"></div>
</div>
<script>
var data = [
	{id:1,parent_id:0,content:'第一个'},
	{id:2,parent_id:0,content:'第二个'},
	{id:3,parent_id:1,content:'回复 第一个'},
	{id:4,parent_id:1,content:'回复 第一个'},
	{id:5,parent_id:3,content:'回复 回复 第一个'},
	{id:6,parent_id:5,content:'回复 回复 回复 第一个'},
	{id:7,parent_id:1,content:'回复 第一个'},
	{id:8,parent_id:2,content:'回复 第二个'},
];

function commentTree(commentList){
	var comment_str = "<div class='comment' >";
	commentList.forEach(function(row) {
		var temps = "<div class='content'>"+row.content+"</div>";
		comment_str += temps;
		console.log(row.children);
		if (row.children && row.children.length>0){
			comment_str +=commentTree(row.children);
		}
	});
	comment_str += "</div>";
	return comment_str;
}

function toTree(data) {
	data.forEach(function(item) {
		delete item.children;
	});
	var map = {};
	data.forEach(function(item) {
		map[item.id] = item;
	});
	var val = [];
	data.forEach(function(item) {
		var parent = map[item.parent_id];
		if (parent) {
			(parent.children || (parent.children = [])).push(item);
		} else {
			val.push(item);
		}
	});
	return commentTree(val);
}

var comment = toTree(data);
document.getElementById('commentArea').innerHTML=comment;
</script>
Edit | Last updated on 2024-03-04 23:34:50




×