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();
});
});
答案 0 :(得分:1)
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/