728x90
반응형
jQuery로 Table의 로우를 추가하거나 제거하는 방법을 구현해보도록 하자.
테이블은 여러 컬럼으로 구성된 경우에는 자바스크립트가 많이 복잡해지는 단점이 있긴 하지만, 구현 방법 자체는 단순하다.
1. HTML 구성
<table id="contentTable" border="1" width="300">
<tr>
<th>기종</th>
<th>제목</th>
</tr>
<tr id="test1">
<td>Xbox360</td>
<td>Gears of War</td>
</tr>
<tr id="test2">
<td>PS3</td>
<td>Resistance</td>
</tr>
</table>
<tr>
<th>기종</th>
<th>제목</th>
</tr>
<tr id="test1">
<td>Xbox360</td>
<td>Gears of War</td>
</tr>
<tr id="test2">
<td>PS3</td>
<td>Resistance</td>
</tr>
</table>
2. JavaScript AddRow 함수 생성
추가하는 함수에는 html 코드가 들어가야한다. 테이블이 컬럼 2개로 구성이 되어있음으로 td가 2개를 만들었다. 추가한 로우 삭제를 위해 tr에 고유 id를 지정하였다.
<script type="text/javascript">
function addRow(){
var rows = jQuery("#contentTable tr");
var index = rows.length;
jQuery("#contentTable").append(
"<tr id='test"+index+"'>"
+"<td>"
+" <a href='javascript:deleteRow("+index+");'> WII</a>"
+"</td>"
+"<td>Mario</td>"
+"</tr>"
);
}
function addRow(){
var rows = jQuery("#contentTable tr");
var index = rows.length;
jQuery("#contentTable").append(
"<tr id='test"+index+"'>"
+"<td>"
+" <a href='javascript
+"</td>"
+"<td>Mario</td>"
+"</tr>"
);
}
</script>
3. JavaScript DeleteRow 함수 생성
삭제하는 함수에는 고유아이디를 받아서 페이드 옵션으로 천천히 사라지게 한후 실제 테이블에서 삭제하는 remove를 호출하였다.
function deleteRow(index)
{
var row = jQuery("#test"+index);
row.fadeOut("slow", function()
{
row.remove();
});
}
{
var row = jQuery("#test"+index);
row.fadeOut("slow", function()
{
row.remove();
});
}
Add를 누르면 기존의 2개 로우에서
3개 로우로 늘어난다.
제목을 클릭하면 다시 삭제 되고, 로우가 2개가 된다.
[출처] jQuery - 동적으로 테이블 관리|작성자 하늘밑
728x90
반응형
'JQUERY > 소스코드' 카테고리의 다른 글
jQuery - Dialog (0) | 2015.02.03 |
---|---|
jQuery indexof (0) | 2015.02.03 |
jQuery - Simple Tree (0) | 2015.02.03 |
onclick 이벤트 제거하기 (0) | 2015.02.03 |
jquery .hover (마우스오버와 마우스아웃) (0) | 2015.02.03 |
ajax로 폼값 받아 div에 출력하는 방법 (0) | 2015.02.03 |
[jquery]radio 버튼 (0) | 2015.02.03 |
[jQuery] jQuery Plugin을 이용한 form validation (0) | 2015.02.03 |