객체 조작 메서드 실습_jQuery

2022. 1. 21. 11:43ksmart_html_css_js/jQuery 실습

728x90
1.
아래의 추가 버튼 클릭 시 행을 복제하여 행 추가, 제거 버튼 클릭 시 행 제거를 하도록 하시오.
(input의 값은 초기화, 삭제시 행 2개 이상일 경우에만 삭제 가능하도록)
<table border="1">
	<tbody>
		<tr>
			<td><input type="text" class="msg"></td>
			<td>
				<button type="button" class="addBtn">추가</button>
				<button type="button" class="delBtn">제거</button>
			</td>
		</tr>
	</tbody>
</table>
1. 답
<script type="text/javascript">
	$(function() {
		var $tr = $('tbody');
		$('.addBtn').click(function() {
			var $clone = $(this).parents('tr').clone(true);
			$tr.append($clone);
		});
		$('.delBtn').click(function() {
			$(this).parents('tr').remove();
			if ($('tr').length < 2)
				return;
		});
	});
</script>
728x90