HTML - 게시글관리
json 을 사용해서 게시글 관리를 만들었다.
<!DOCTYPE html>
<html>
<head>
<title>블로그</title>
<link rel="preconnect" href="https://fonts.googleapis.com">
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
<link href="https://fonts.googleapis.com/css2?family=Jua&family=Sunflower:wght@300&display=swap" rel="stylesheet">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<link rel="stylesheet" href="common.css"/>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<style>
#posts {border : 4px solid #DDA94B; margin :10px ; padding:20px}
button:disabled {background-color: antiquewhite; color: black;}
</style>
</head>
<body>
<div id ="page">
<div id ="top">
<h1>게시글관리</h1>
</div>
<div id ="center">
<div id ="posts" style="color: white;"></div>
<div id ="buttons">
<button id ="prev">이전</button>
<span id ="curpage" style ="color: white;">1</span>
<button id="next">다음</button>
</div>
</div>
</div>
</body>
<script>
let curpage =1; //현재페이지
let perpageNum=10;
let lastPage=Math.ceil(100/perpageNum);
$("#curpage").html(curpage+"/"+lastPage);
getList();
//다음버튼을 클릭한경우
$("#next").on("click", function(){
curpage++;
$("#curpage").html(curpage +"/"+lastPage);
getList();
});
//이전버튼을 클릭한 경우
$("#prev").on("click", function(){
curpage--;
$("#curpage").html(curpage+"/"+lastPage);
getList();
});
function getList(){
$.ajax({
type: "get",
dataType: "JSON",
url :"https://jsonplaceholder.typicode.com/posts",
success : function(data){
let str ="";
$(data).each(function(){
let id =this.id;
let title=this.title;
let body = this.body;
let start = (curpage-1)*perpageNum +1;
let end = (curpage)*perpageNum
if(id>=start && id<=end) {
str += "<h3>" +id +":" +title+"</h3>";
str += "<p>" + body + "</p>"+"<br>";
}
});
$("#posts").html(str);
// 1페이지인 경우 이전버튼 클릭 불가능
if(curpage==1) {
$("#prev").attr("disabled",true);
}else {
$("#prev").attr("disabled",false);
}
// 현재페이지가 마지막페이지 일때 다음버튼 클릭불가능
if(curpage==lastPage){
$("#next").attr("disabled",true);
}else {
$("#next").attr("disabled",false);
}
}
});
};
</script>
</html>
데이타를 json 에서 가져왔다. 페이지를 perpageNum으로 10페이지를 줬고 이전 다음 버튼을 줘서 페이지가 이동가능하게했다. 페이지 범위 밖으로 벗어났을때 클릭이 눌리지 않도록 구현했다.
댓글남기기