javascript - event dom

yeong ·2022년 11월 22일

js

목록 보기
47/49

이벤트(Event) - DHTML(Dynamic HTML
DHTML : 태그에서 이벤트가 발생될 경우 태그에 대한 Element 객체를 조작하여 동적인 페이지 제공하는 기능

<style type="text/css">
#itemListDiv div {
	margin: 5px;
}
</style>
</head>
<body>
	<h1>이벤트(Event) - DHTML(Dynamic HTML)</h1>
	<hr>
	<p>DHTML : 태그에서 이벤트가 발생될 경우 태그에 대한 Element 객체를 조작하여 
	동적인 페이지 제공하는 기능</p>
	<hr>
	<button type="button" id="addBtn">아이템 추가</button>
	<div id="itemListDiv"></div>
	
	<script type="text/javascript">
	var count=0;//태그를 구분하기 위한 값을 저장하기 위한 변수
	
	document.getElementById("addBtn").onclick=function() {
		count++;
		
		var newItem=document.createElement("div");//<div></div>
		newItem.setAttribute("id", "item_"+count);//<div id="item_XXX"></div> 추후에 삭제하기위한 식별자 id
		var html="아이템["+count+"]&nbsp;&nbsp;";
		html+="<button type='button' onclick='removeItem("+count+");'>삭제</button>"; //태그를 구별할 고유값 count을 전달 
		newItem.innerHTML=html;//<div id="item_XXX">아이템[XXX] [삭제]</div>
		
		document.getElementById("itemListDiv").appendChild(newItem);
	}
	
	function removeItem(cnt) {
		//alert(cnt);
		
		var removeElement=document.getElementById("item_"+cnt);
		document.getElementById("itemListDiv").removeChild(removeElement);
	}
	</script>
</body>

0개의 댓글