jQuery 是一个快速、小巧且功能丰富的 JavaScript 库,它简化了 HTML 文档遍历、事件处理、动画和 Ajax 交互。Laravel 是一个基于 PHP 的全栈框架,提供了构建现代 Web 应用程序所需的各种工具和功能。
假设我们有一个简单的表单,用户可以输入多个商品的数量和单价,我们需要使用 jQuery 自动计算总价。
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>自动计算总价</title>
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
</head>
<body>
<form id="productForm">
<div class="product">
<input type="number" name="quantity[]" placeholder="数量">
<input type="number" name="price[]" placeholder="单价">
</div>
<button type="button" id="addProduct">添加商品</button>
<button type="submit">提交</button>
</form>
<div>总价: <span id="totalPrice">0</span></div>
<script src="script.js"></script>
</body>
</html>
$(document).ready(function() {
let totalPrice = 0;
function updateTotalPrice() {
totalPrice = 0;
$('.product').each(function() {
let quantity = $(this).find('input[name="quantity[]"]').val() || 0;
let price = $(this).find('input[name="price[]"]').val() || 0;
totalPrice += parseFloat(quantity) * parseFloat(price);
});
$('#totalPrice').text(totalPrice.toFixed(2));
}
$('#productForm').on('input', '.product input', updateTotalPrice);
$('#addProduct').click(function() {
$('.product').first().clone().appendTo('#productForm');
});
$('#productForm').submit(function(event) {
event.preventDefault();
// 这里可以发送数据到 Laravel 后端进行处理
console.log('Total Price:', totalPrice);
});
});
原因:
解决方法:
$(document).ready()
确保 DOM 完全加载后再执行 jQuery 代码。on
方法绑定动态添加的元素。parseFloat
确保数量和单价是数字类型。通过以上步骤,你可以实现一个简单的自动计算总价的功能,并且了解相关的概念和解决方法。
没有搜到相关的沙龙