2015-09-24 111 views
0

这是一个简单的问题,我已经编写了一个简单的计算函数,它完美地工作,尽管我遇到了一个问题,因为它仅适用于.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); 


}); 
+3

什么是'$(this)'应该是?当你第一次调用compute()时,'$(this)'将等于整个DOM - 不知道它最接近'tr'元素是什么,但它可能不是你想要的目标。 –

+0

井把戒备(排); var row = $(this).closest('tr');并看看你得到了什么 – dansasu11

+0

“包含在页脚中”。在你有'document.ready()'之前,你不应该加载这个库吗? –

回答

1

可以触发与change()初始状态的变化。这为呼叫保留了正确的this范围:

例如

$('.price, .quantity').change(compute).change(); 

但代码需要在同一范围内的函数调用,也可以不看功能:

$(document).ready(function() { 
    function compute() { 
     // Snip... 
    }); 
    $('.price, .quantity').change(compute).change(); 
}); 

从技术上讲,你可能不想触发的所有比赛中,哪种情况下的触发器更改只有first

$('.price, .quantity').change(compute).first().change(); 
6

,因为它仅与.change()方法,工作并没有当文档被装载

你的功能是指this

... 
var row = $(this).closest('tr'); 
... 

调用时从.change处理程序,这意味着this这基本上是“已改变的元素” - 所以你的方法工作得很好。

当没有这个环境下调用时,this没有相关的含义 - 它几乎肯定是指window

+1

嗯,任何工作,我有一个表有多行,每一行都有一个输入与金额和输入与价格。谢谢Jamiec的解释 – Svedr

1

$(this)对应于当前对象/元素。当您的功能在.ready()内时,$(this)与该文档无关并且指向该文档。

当从.change()事件调用相同时,$(this)现在对应于已更改的元素,因此它工作。

要使它在.ready()中工作,您需要首先找到与特定元素最接近的tr,而不是$(this)。为此,您可以使用Id并声明像明智的功能。

0

你保持你的函数定义出的document.ready()的侧面,如下

$(document).ready(function() { 
    compute(); // this is where I am trying to start the function on load 
$('.price, .quantity').change(compute); 
}); 
function compute() { 
var row = $('.price, .quantity').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); 

} 
相关问题