|
 |
|
ของความช่วยเหลือหน่อยครับ อยากทำปุ่มกดบวกตัวเลขครับ |
|
 |
|
|
 |
 |
|
ทำได้แค่ไหน ทำแล้วไม่ได้ตรงไหน เอาโค้ดมาดูครับ
|
 |
 |
 |
 |
Date :
2021-08-30 09:36:58 |
By :
mr.v |
|
 |
 |
 |
 |
|
|
 |
 |
|
 |
 |
 |
|
|
 |
 |
|
DOM
Code (PHP)
<input type="text" id="total" value="0" readonly>
<button type="button" class="btn-plus" value="5">5</button>
<button type="button" class="btn-plus" value="10">10</button>
<button type="button" class="btn-plus" value="15">15</button>
<button type="button" class="btn-plus" value="20">20</button>
<button type="button" id="clear">Clear</button>
<script>
var btn = document.querySelectorAll('.btn-plus');
var total = document.getElementById('total');
var clear = document.getElementById('clear');
clear.addEventListener('click', function(event) {
total.value = 0;
});
btn.forEach(el => el.addEventListener('click', event => {
total.value = parseInt(total.value) + parseInt(el.value);
}));
</script>
ส่วน jQuery ชีวิตก็ง่ายขึ้นอีก
|
 |
 |
 |
 |
Date :
2021-08-30 11:01:13 |
By :
Guest |
|
 |
 |
 |
 |
|
|
 |
 |
|
 |
 |
 |
|
|
 |
 |
|
Code (JavaScript)
<html>
<head>
<title>Calculadora Basica</title>
</head>
<body>
<input name="price[]" type="text" id="show">
<input type="button" id="txt" value="5" class="calc-button">
<input type="button" id="txt" value="10" class="calc-button">
<input type="button" id="txt" value="15" class="calc-button">
<input type="button" id="txt" value="20" class="calc-button">
<script type="application/javascript">
document.addEventListener('click', (event) => {
if (event.target && event.target.classList.contains('calc-button')) {
event.preventDefault();
} else {
return false;
}
let thisButton = event.target;
let displayElement = document.getElementById('show');
let displayValue = displayElement.value;
if (displayValue === '') {
displayValue = 0;
}
displayValue = (parseInt(displayValue) + parseInt(thisButton.value));
displayElement.value = displayValue;
});
</script>
</body>
</html>
วิธีที่ผมเขียนนี้เรียกว่า event delegation เอาไว้ดักคลิกอย่างกว้างๆก่อน แล้วค่อยหาเงื่อนไขว่าใช่คลิกที่ต้องการหรือไม่ แล้วจึงทำงาน
ข้อดีคือถ้ามีปุ่มเยอะๆมันจะทำงานเร็วกว่าวิธีอื่น ( ผลทดสอบ https://www.thaicreate.com/community/forum/135841.html#3 )
|
ประวัติการแก้ไข 2021-08-30 13:46:32 2021-08-30 13:46:50 2021-08-30 13:47:20
 |
 |
 |
 |
Date :
2021-08-30 13:41:22 |
By :
mr.v |
|
 |
 |
 |
 |
|
|
 |
 |
|
 |
 |
|
|
|

|
Load balance : Server 03
|