代码计算服务列表的总价格。我为每个服务都有一个输入标签。修改服务价格时,将计算总价。
$(document).on('change key paste keyup', '[id^="bill_servicesPerformed"][id$="unitPrice"]', function() {
//here the code to calculate the total price
}
现在,我还想计算从列表中删除其中一个服务时的总数。如何重复使用代码来计算总价?
注意:当然,在每个服务旁边,我都有一个带有"删除服务"类的链接。
删除
它们时,您必须手动启动该逻辑。 目前,在更广泛地实现观察者之前,没有一种很好的方法来检测元素是否已从 DOM 中添加/删除并因此执行某些操作。 当然,据我所知,这是事实。
为函数命名。 然后你可以调用它。 匿名函数仅在需要将其作为参数传递一次时才有用。
例:
function updatePrices() {
//here the code to calculate the total price
}
$(document).on('change key paste keyup', '[id^="bill_servicesPerformed"][id$="unitPrice"]', updatePrices);
$(document).on('click', 'a.remove-service', updatePrices);
var calculateTotalPrice = function() {
//calculator algorithm here
}
$(document).on('change key paste keyup', '[id^="bill_servicesPerformed"][id$="unitPrice"]', calculateTotalPrice);
$('a.remove-service-link').click(function(e) {
// to prevent run the a href
e.preventDefault();
// your remove service code here
// then call calculate function
calculateTotalPrice();
});