这是一个简单的问题,我已经编写了一个简单的计算函数,它完美地工作,尽管我遇到了一个问题,因为它仅适用于.change()方法,并且不会在加载文档时使用。我编写的这个函数依赖于包含在页脚中的数字库。为什么此功能在页面加载时不运行?
$(document).ready(function() {
function compute() {
var row = $(this).closest('tr');
var price = parseFloat($('.price', row).val().replace(',', '.'));
var quantity = parseFloat($('.quantity', row).val(), 10);
var total = price * quantity;
totalCleaned = numeral(total.toFixed(2)).format('0,0.00');
$('.total', row).html(totalCleaned);
var grandTotal = 0;
var totalsum = 0;
$('.total').each(function() {
totalsum += numeral().unformat($(this).text());
grandTotal = numeral(totalsum.toFixed(2)).format('0,0.00');
$('.net-total').html(grandTotal);
});
console.log(grandTotal);
}
compute(); // this is where I am trying to start the function on load
$('.price, .quantity').change(compute);
});
什么是'$(this)'应该是?当你第一次调用compute()时,'$(this)'将等于整个DOM - 不知道它最接近'tr'元素是什么,但它可能不是你想要的目标。 –
井把戒备(排); var row = $(this).closest('tr');并看看你得到了什么 – dansasu11
“包含在页脚中”。在你有'document.ready()'之前,你不应该加载这个库吗? –