我使用以下功能计算产品的总价格:
jQuery(document).ready(function() {
function j_updateprice() {
var p = 0;
jQuery('.am-signup-form input[type=radio][id^=product]:checked,
.am-signup-form input[type=checkbox][id^=product]:checked')
.each(function(i, v) {
if (jQuery(v).attr('data-first_price')) {
p += parseFloat(jQuery(v).attr('data-first_price'));
}
});
jQuery('#j_price').text(p.toFixed(2));
}
jQuery('.am-signup-form input[type=radio][id^=product],
.am-signup-form input[type=checkbox][id^=product]')
.change(function() {
j_updateprice();
});
j_updateprice();
});
问题是,当我点击另一个div的复选框/单选按钮时,价格会不断加起来(它不应该)。所以我想在应用#j_price
之前清空总数(j_updateprice()
):
jQuery('.am-signup-form input[type=radio][id^=product],
.am-signup-form input[type=checkbox][id^=product]')
.change(function() {
jQuery('#j_price').empty();
j_updateprice();
});
但没有任何反应。价格不断加起来。那是为什么?
答案 0 :(得分:3)
您应该考虑所选面板中的已检查元素,现在您正在考虑表单中包含以前所选面板中的项目的所有已检查项目
jQuery(document).ready(function () {
function j_updateprice() {
var p = 0;
jQuery('.am-signup-form .panel-expanded input[type=radio][id^=product]:checked, .am-signup-form .panel-expanded input[type=checkbox][id^=product]:checked').each(function (i, v) {
if (jQuery(v).attr('data-first_price')) p += parseFloat(jQuery(v).attr('data-first_price'));
});
jQuery('#j_price').text(p.toFixed(2));
}
jQuery('.am-signup-form input[type=radio][id^=product], .am-signup-form input[type=checkbox][id^=product]').change(function () {
j_updateprice();
});
j_updateprice();
});
注意:更改所选面板时,您还必须致电j_updateprice