웹
(웹)DOM 테이블 추가,삭제/사용자가 원하는 만큼 테이블 추가 삭제 예제(결과화면 有)
공부가싫다가도좋아
2021. 5. 11. 11:51
반응형
DOM을 사용한 테이블 만들기
결과화면을 보신다음,
혼자서 코드를 작성한 후, 제 코드를 보시는걸 권장 드립니다.
* 결과 화면
<작성 버튼 클릭 시>
1. 버튼안의 value는 초기화로 바뀜
2. 행과 열의 value에 따라 테이블 생성
<초기화 버튼 클릭 시>
1. 버튼안의 value는 작성으로 바뀜
2. 행과 열의 value는 1로 바뀜
3. 테이블 삭제
* 코드 및 설명
<!DOCTYPE html>
<html lang="ko">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Test 2</title>
<style>
form{
margin: 10px;
}
input[type="text"]{
width: 20px;
margin-right: 5px;
}
button{
margin-left: 10px;
}
table, td{
border: 1px solid black;
border-collapse: collapse;
}
td{
padding: 10px;
}
</style>
</head>
<body>
<form>
<input id="row" type="text" value="1"><label>행</label>
<input id="column" type="text" value="1"><label>열</label>
<input type="button" id="btn" onclick="drawTable();" value="작성">
</form>
<div id="contents"></div>
<script>
cnt = 0; //버튼 value와 다른 동작을 위한 전역 변수
function drawTable(){
if(cnt === 0){ // cnt가 0일때
btn = document.getElementById("btn");
btn.value = '초기화'; //버튼 value 초기화로 바꿈
//테이블요소 추가 밎 사용자가 입력한 행과 열 value 가져옴.
let row = document.querySelector("#row").value;
let col = document.querySelector("#column").value;
let table = document.createElement("table");
//행과 열의 value 만큼 td와 tr 요소 추가
for(let i=0;i<row;i++){
let tr = document.createElement("tr");
for(let j=0;j<col;j++){
let td = document.createElement("td");
let txt = document.createTextNode((i+1) + "," + (j+1));
td.appendChild(txt);
tr.appendChild(td);
}
table.appendChild(tr);
}
let contents = document.querySelector("#contents");
contents.appendChild(table);
cnt = 1;
}
else{ //cnt가 1일때
btn = document.getElementById("btn");
let table = document.querySelector("table");
btn.value = '작성'; //버튼의 value를 작성으로 바꿈
//행과 열 안의 value를 1로 초기화 시켜줌.
document.getElementById("row").value = "1";
document.getElementById("column").value = "1";
//초기화를 위해 테이블요소를 지움.
if(table.parentNode){
table.parentNode.removeChild(table);
}
cnt = 0;
}
}
</script>
</body>
</html>
반응형