jQuery Addition

时间:2011-01-18 06:57:34

标签: jquery addition

我正在尝试将两个值与jQuery一起添加。我有一个包含这些值的表:

<table>
<tr id="fc_cart_foot_subtotal">
<td class="fc_col2">$7.95</td>
</tr>
<tr id="fc_cart_foot_shipping">
<td class="fc_col2">$4.00</td>
</tr>
<tr id="fc_cart_foot_total">
<td class="fc_col2">$7.95</td>
</tr>
</table>

我需要添加#fc_cart_foot_subtotal .fc_col2的值:

<tr id="fc_cart_foot_subtotal">
<td class="fc_col2">$7.95</td>
</tr>

到#fc_cart_foot_shipping .fc_col2:

的值
<tr id="fc_cart_foot_shipping">
<td class="fc_col2">$4.00</td>
</tr>

并更新了#fc_cart_foot_total .fc_col2的值

<tr id="fc_cart_foot_total">
<td class="fc_col2">$7.95</td>
</tr>

所以在这个例子中,$ 7.95的第一个小计值应该加4.00美元,总计11.95美元。小计和运费会发生变化,所以我需要能够“抓住”这些值,因为它们会改变并在等式中使用它们。

1 个答案:

答案 0 :(得分:0)

将美元字符串转换为要添加的数字:

function parseDollar(str) {
   return +str.substr(1);
}

然后将数字加在一起并正确格式化:

$('#fc_cart_foot_total .fc_col2').text('$' + (
    parseDollar($('#fc_cart_foot_subtotal .fc_col2').text()) +
    parseDollar($('#fc_cart_foot_shipping .fc_col2').text())
).toFixed(2));

如果您可能获得负的美元价值,例如“ - $ 1.00”,然后将parseDollar更改为:

function parseDollar(str) {
    return +str.replace(/\$/, '');
}