这是一个简单的问题,我编写了一个简单的计算函数,虽然我遇到了一个问题但它工作得很好,因为它只适用于.change()方法,而不是在加载文档时.我编写的这个函数依赖于页脚中包含的Numerals库.
$(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);
});
Run Code Online (Sandbox Code Playgroud)
因为它只适用于.change()方法,而不是在加载文档时
你的功能是指this:
...
var row = $(this).closest('tr');
...
Run Code Online (Sandbox Code Playgroud)
当从.change处理程序调用时,this这个本质上意味着"已经改变的元素" - 所以你的方法工作得很好.
在没有这个上下文的情况下调用时,this没有相关意义 - 它几乎肯定是指window.