为什么此功能在页面加载时没有运行?

时间:2015-09-24 10:40:36

标签: javascript jquery

这是一个简单的问题,我编写了一个简单的计算函数,虽然我遇到了问题,但它的工作原理很完美,因为它只适用于.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);


});

4 个答案:

答案 0 :(得分:6)

  

因为它只适用于.change()方法,而不是在加载文档时

您的功能是指new MyTwitterApiClient(session).getCustomService().show(userID, null, true, true, 100, new Callback<User>() { @Override public void success(Result<User> result) { LogUtils.LOGI("Get success",result.toString()); } @Override public void failure(TwitterException e) { hideProgressDialog(); } });

this

... var row = $(this).closest('tr'); ... 处理程序调用时,.change的含义基本上是“已更改的元素” - 所以你的方法运行正常。

在没有此上下文的情况下调用时,this没有相关含义 - 它几乎肯定会引用this

答案 1 :(得分:1)

$(this)对应于当前对象/元素。当您的函数位于.ready()内时,$(this)没有相关性并且会引用该文档。

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

要使其在.ready()中有效,您需要首先找到与$(this)特定元素相关的最接近的tr。为此,您可以使用Id并将该函数声明为明智。

答案 2 :(得分:1)

您可以使用change()触发初始状态更改。这保留了正确的this通话范围:

e.g。

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

但代码需要与它调用的函数在同一范围内,否则它无法看到函数:

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

从技术上讲,您可能不希望在所有匹配项上触发,在这种情况下仅在first上触发更改:

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

答案 3 :(得分: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);

}
相关问题