【发布时间】:2016-02-13 23:24:23
【问题描述】:
今天我尝试从<span> 值和<input> 值计算价格。然后,将结果放入<span>。
我已经尝试过这段代码。这是我的html:
<td class="cart-product-price">
<span id="price" class="amount">19.99</span>
</td>
<td class="cart-product-quantity">
<div class="quantity clearfix">
<input type="button" value="-" class="minus" field="quantity">
<input type="text" id="quantity" name="quantity" value="2" class="qty" />
<input type="button" value="+" class="plus" field="quantity">
</div>
</td>
<td class="cart-product-subtotal">
<span id="total" class="amount"></span>
</td>
所以我想从<span id="price>获取价格值,从<input type="text" id="quantity" name="quantity">获取数量,并将结果放入<span id="total" class="amount"></span>
这是我的脚本代码:
<script type="text/javascript">
var price = parseFloat($('#price').val()) || 0;
var qty = parseInt($('input[name=quantity]').val());
var total = price*qty;
$('#total').text(total);
</script>
注意:我使用 JQuery 来增加/减少数量(加号和减号按钮)
我写错了吗?
谢谢
更新
这是我增加/减少的javascript代码:
<script type="text/javascript">
jQuery(document).ready(function(){
// This button will increment the value
$('.plus').click(function(e){
// Stop acting like a button
e.preventDefault();
// Get the field name
fieldName = $(this).attr('field');
// Get its current value
var currentVal = parseInt($('input[name='+fieldName+']').val());
// If is not undefined
if (!isNaN(currentVal)) {
// Increment
$('input[name='+fieldName+']').val(currentVal + 1);
} else {
// Otherwise put a 0 there
$('input[name='+fieldName+']').val(0);
}
});
// This button will decrement the value till 0
$(".minus").click(function(e) {
// Stop acting like a button
e.preventDefault();
// Get the field name
fieldName = $(this).attr('field');
// Get its current value
var currentVal = parseInt($('input[name='+fieldName+']').val());
// If it isn't undefined or its greater than 0
if (!isNaN(currentVal) && currentVal > 0) {
// Decrement one
$('input[name='+fieldName+']').val(currentVal - 1);
} else {
// Otherwise put a 0 there
$('input[name='+fieldName+']').val(0);
}
});
});
</script>
【问题讨论】:
-
您是否尝试调试过您的代码?你在你的 JS 函数中看到 price 和 qty 的值了吗? #total 得到什么结果?
标签: javascript jquery html