본문 바로가기
HTML│CSS│Java Script

html 표 추가 삭제

by 자유코딩 2017. 12. 6.

html 표에 행을 추가하고 삭제하기

 

코드

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
<style type="text/css">
    /*아이디 선택자가 #인 것을 지칭*/
    #table1{width:70%}
    #table2{width:50%}
    table,th,td{border:1px solid black;text-align:center;}
</style>
<script type="text/javascript">
    function add_go() {
        //태그 생성
        var td1=document.createElement("td");
        var td2=document.createElement("td");
        var td3=document.createElement("td");
        
        var tr = document.createElement("tr");
        //만들 태그에 문자(텍스트) 삽입
        td1.innerHTML="1";
        td2.innerHTML="fors";
        td3.innerHTML="010-1234-5678";
        
        //tr안에 td붙이기
        tr.appendChild(td1);
        tr.appendChild(td2);
        tr.appendChild(td3);
        
        //tbody에 tr붙이기
        
        /* document.getElementById("tbody").appendChild(tr); */
        document.getElementById("table1").children[2].appendChild(tr);
    }
     function delete_go() {
            var my_tbody = document.getElementById('my-tbody');
            if (my_tbody.rows.length < 1return;
            // my_tbody.deleteRow(0); // 상단부터 삭제
            my_tbody.deleteRow( my_tbody.rows.length-1 ); // 하단부터 삭제
          }
</script>
</head>
<body>
    <table id="table1">
        <thead>
            <tr>
                <th>번호</th>
                <th>이름</th>
                <th>전화</th>
            </tr>
        </thead>
        
        <tfoot>
            <tr>
                <td>
                    <input type="button" value="추가" onclick="add_go()">
                </td>
                <td>
                    <input type="button" value="삭제" onclick="delete_go()">
                </td>
            </tr>
        </tfoot>            
        <tbody id="my-tbody">
            <tr></tr>
        </tbody>
    </table>
    
    
    <table id="table2">
        <thead>
            <tr>
                <th>번호</th>
                <th>이름</th>
                <th>전화</th>
            </tr>
        </thead>
        <tbody id=>
            <tr></tr>
        </tbody>
        <tfoot>
            <tr>
                <td colspan="3">
                    <input type="button" value="추가" onclick="add_go()">
                </td>
            </tr>
        </tfoot>            
    </table>
    
</body>
</html>
cs

 

 

'HTML│CSS│Java Script' 카테고리의 다른 글

p 태그 id에 자바스크립트 결과 담기  (0) 2017.12.06
html 전구 켜고 끄기  (0) 2017.12.06
html 예제  (0) 2017.12.05
html 회원 정보 확인 예제  (0) 2017.12.05
html 회원가입 양식  (0) 2017.12.05

댓글