เครื่องคิดเลขสินค้าใน 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');
คัดลอกโค้ดตัวอย่างที่ฉันเตรียมไว้ให้ ไปที่ตัวคุณเอง