Chỉnh sửa với tính toán lại trong máy tính sản phẩm bằng JavaScript
Bây giờ hãy hoàn thiện hàm allowEdit
để thực hiện việc tính toán lại đã được mô tả trong
bài học trước.
Đến thời điểm này, mã code của hàm của bạn nên trông đại khái như thế này:
function allowEdit(td) {
td.addEventListener('dblclick', function() {
let text = td.textContent
td.textContent = '';
let input = document.createElement('input');
input.value = text;
input.focus();
td.appendChild(input);
input.addEventListener('keydown', function(event) {
if (event.key == 'Enter') {
td.textContent = this.value;
}
});
});
}
Chúng ta hãy thêm mã code, sẽ thực hiện tính toán lại cho ô chứa giá và cho ô chứa số lượng:
function allowEdit(td) {
td.addEventListener('dblclick', function() {
let text = td.textContent
td.textContent = '';
let input = document.createElement('input');
input.value = text;
input.focus();
td.appendChild(input);
input.addEventListener('keydown', function(event) {
if (event.key == 'Enter') {
td.textContent = this.value;
if (td.classList.contains('price') || td.classList.contains('amount')) {
// thực hiện tính toán lại
}
}
});
});
}
Hãy viết bổ sung phần mã code còn thiếu sao cho
khi thay đổi ô chứa giá hoặc ô chứa
số lượng thì chi phí mua hàng
ở cột cost sẽ thay đổi, đồng thời
thực hiện tính toán lại tổng số tiền.