本文旨在解决在使用 jQuery 计算动态添加的元素总金额时,页面初始加载时总金额显示为 0 的问题。通过修改事件绑定方式,并在适当的时机调用计算总金额的函数,确保总金额能够正确地随着用户选择而更新。同时,避免在HTML中直接使用事件监听器,采用`.addEventListener`实现更佳的代码可维护性。
在使用 jQuery 开发 Web 应用时,经常需要动态计算页面元素的值,并显示总金额。一个常见的问题是,当页面加载时,由于某些元素是动态生成的,jQuery 可能无法立即获取到这些元素,导致计算出的总金额为 0。本文将详细介绍如何解决这个问题,并提供一个可行的解决方案。
问题的根源在于 jQuery 的 $(document).ready() 函数只在页面加载完成后执行一次。如果在 ready 函数执行时,动态添加的元素尚未生成,那么 jQuery 就无法获取到这些元素,导致总金额计算错误。
为了解决这个问题,我们需要在每次动态添加元素后,都重新计算总金额。具体步骤如下:
以下是修改后的代码:
function selectedAfternoon(element) {
var text = element.options[element.selectedIndex].value;
document.getElementById("output-selected-option-afternoon").innerHTML = "" + text.split("|").join("") + "";
document.getElementById("output-selected-option-afternoon").querySelector("div:last-child").classList.add("priceSelectedOption")
computeTotal()
}
function selectedCommute(element) {
var text = element.options[element.selectedIndex].value;
document.getElementById("output-selected-option-commute").innerHTML = "" + text.split("|").join("") + "";
document.getElementById("output-selected-option-commute").querySelector("div:last-child").classList.add("priceSelectedOption")
computeTotal()
}
function computeTotal() {
var total = 0;
$('.priceSelectedOption').each(function() {
total += parseFloat($(this).text().replace(/,/g, ''))
})
$('.totalPrice').text(total)
}
$(document).ready(function() {
document
.getElementById('Onderweg')
.addEventListener('change', function() { selectedCommute(this) })
document
.getElementById('Namiddag')
.addEventListener('change', function() { selectedAfternoon(this) })
computeTotal()
})Total
CSS 代码保持不变
.js-basic-single {
width: 100%;
}
#output-selections {
display: flex;
flex-direction: column;
grid-column-gap: 1rem;
grid-row-gap: 1rem;
}
.selected-option {
display: flex;
width: 100%;
flex-direction: row;
justify-content: space-between;
align-items: center;
}
.priceSelectedOption::before,
.totalPrice::before {
content: '€ ';
}通过以上步骤,可以有效地解决在使用 jQuery 计算动态添加的元素总金额时,页面初始加载时总金额显示为 0 的问题。 关键在于在每次动态添加元素后,都重新计算总金额,并使用 addEventListener 来绑定事件监听器,避免在 HTML 中直接绑定事件监听器。 这种方法可以确保总金额能够正确地随着用户选择而更新,并提高代码的可维护性和可读性。