JavaScript로 만든 식품 계산기
이 섹션에서는 식품 계산기를 구현할 것입니다. 이는 사용자가 자신의 구매 내역을 입력할 수 있는 표 형태가 될 것입니다.
구매 내역은 양식을 통해 입력되도록 합니다. 또한 각 제품에 대해 삭제 링크를 제공하겠습니다. 제품의 이름, 가격 및 수량을 편집할 수 있는 기능도 만들겠습니다. 이러한 편집은 표 셀을 더블 클릭하여 수행되도록 합니다.
표 아래에는 제품들의 총 비용이 표시되도록 합니다. 제품을 삭제하거나 편집할 때 이 합계가 다시 계산되도록 만듭니다.
결과물의 예시는 다음과 같습니다:
문제를 해결하는 데 사용할 수 있는 마크업은 다음과 같습니다:
<div id="parent">
<div id="form">
<input id="name" placeholder="이름">
<input id="price" placeholder="가격">
<input id="amount" placeholder="수량">
<input id="add" type="button" value="추가">
</div>
<h2>제품 테이블:</h2>
<table id="table">
<tr>
<th>이름</th>
<th>가격</th>
<th>수량</th>
<th>합계</th>
<th>삭제</th>
</tr>
</table>
<div id="result">
총계: <span id="total">0</span>
</div>
</div>
* {
box-sizing: border-box;
}
#parent {
margin: 0 auto;
width: 500px;
}
#form {
display: flex;
margin-bottom: 15px;
}
#form input {
padding: 8px;
width: 24%;
margin: 0 0.5% 10px 0.5%;
}
h2 {
margin-top: 0;
margin-bottom: 7px;
}
#table {
width: 100%;
margin-bottom: 10px;
}
#table td, #table th {
padding: 8px;
text-align: center;
border: 1px solid black;
}
#table td.remove {
color: blue;
cursor: pointer;
text-decoration: underline;
}
#table td.remove:hover {
text-decoration: none;
}
#result {
text-align: right;
margin-right: 10px;
}
먼저 필요한 모든 태그에 대한 참조를 변수로 가져옵니다:
let name = document.querySelector('#name');
let price = document.querySelector('#price');
let amount = document.querySelector('#amount');
let add = document.querySelector('#add');
let table = document.querySelector('#table');
let total = document.querySelector('#total');
제가 제공한 코드 템플릿을 복사하세요.