簡體   English   中英

有一個updateTotal()未定義的錯誤。 updateTotal()函數似乎已正確定義和調用。 為什么會出現此錯誤?

[英]Got an updateTotal() not defined error. updateTotal() Function seems to be defined and called appropriately. Why would I be getting this error?

未定義updateTotal()函數,但是,我在$(document).ready(function(){內定義了該函數,並在需要使用它的其他方法內調用了updateTotal()。運行總計未更新。顯示未定義的updateTotal()為什么會出現此錯誤?

$(document).ready( function () {

 $('#plan').on('change', function() {
   var priceText;

   switch(this.value) {
     case 'monthly':
      priceText = '10.00 /mo';
      break;
     case 'quarterly':
      priceText = '$9.00 /mo';
      break;
     case 'yearly':
      priceText = '7.00 /mo';
      break;
   }

   $('#price').text(priceText)
  });

 function updateTotal() {
  var total = 0;

  var entries = $('.entry')

  if (entries.length)
    $('#empty').show();
  else
    $('#empty').hide();

  $('.entry').each( function(index, entry) {
    var data = $(entry).data();
    var price = parseFloat(data.price)
    var installment = data.plan
    switch(installment) {
      case 'monthly':
        total += price;
        break;
      case 'quarterly':
        total += price * 4;
        break;
      case 'yearly':
        total += price * 12;
        break;
    }
  })

  $('#total').text('$' + total);
}
});


$('#add').on('click', function() {
  var plan = $('#plan')
  var installment = plan.val();
  var price = $('#price').text();
  var inCart = $('#in_cart');
  var numeric = price.replace(/[[A-Za-z$\/\s]/g, '');
  var data = 'data-price="' + numeric + '" data-plan="' + 
  installment + '"';
  inCart.append('<li>' + installment + ' - ' + price + '<button 
 class="remove">X</button></li>')
  updateTotal();
});

  $(document).on('click', '.remove', function() {
  $(this).parents('li').remove();
  $('#empty').on('click', function() {
    $('#in_cart').empty();
    updateTotal();
  });

});

JavaScript中的函數在全局范圍或函數范圍內,因此updateTotal僅在document.ready函數中可見。

您應該嘗試在全局范圍(在document.ready之外)中定義updateTotal ,或者使用IIFE( https://developer.mozilla.org/en-US/docs/Glossary/IIFE )創建一些通用范圍,以免也不填充全局范圍許多。

有關范圍界定的一些信息: https : //www.sitepoint.com/demystifying-javascript-variable-scope-hoisting/

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM