본문 바로가기

Programming/Javascript

준비물 메모장 구현 실습

css.zip
0.00MB

<!doctype html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>여행 준비물 점검 목록</title>
<link rel="stylesheet" href="css/input.css">
<link rel="stylesheet" href="css/list.css">
</head>
<body>
	<div id="wrapper">
		<h2>여행 준비물 점검 목록</h2>
		<form onsubmit="return false">
			<!-- 엔터 눌러도 전송되지 않는 속성 -->
			<input type="text" id="item" autofocus="true">
			<button type="button" id="add" class="addBtn">추가</button>
		</form>
		<div id="itemList"></div>
	</div>
	<script type="text/javascript">
		var items = [];

		var item = document.querySelector('#item');
		var btn = document.querySelector('#add');
		var itemList = document.querySelector('#itemList');

		btn.addEventListener('click', addItem);

		function addItem() {
			items.push(item.value);
			item.value = "";
			item.focus();
			show();
		}

		function show() {
			var html = "<ul>";
			for (var i = 0; i < items.length; i++) {
				html += "<li>";
				html += items[i]
						+ "<span class='close' id='" + i + "'>x</span>"
						+ "</li>";
			}
			html += "</ul>";
			itemList.innerHTML = html;

			var spans = document.querySelectorAll('.close');
			for (var i = 0; i < spans.length; i++) {
				spans[i].addEventListener('click', removeItem);
			}

		}

		function removeItem() {
			var index = this.getAttribute('id');
			items.splice(index, 1);
			show();
		}
	</script>
</body>
</html>