2013-01-10 46 views
0

我仍然在学习jQuery和我在GSP有这样的代码:计算值使用jQuery

<g:each in="${poundList}" var="poundInstance"> 
    <span>${poundInstance?.name}<span/> 
    <span class="price">${poundInstance?.price}<span/> 
</g:each> 
    <span id="total"></span> 

在我的jquery:

function calculatePound() { 
    totals= 0; 
$(".price").each (function() { 
    totals= totals+ parseFloat("0" + $(this).val()); 
}); 
$("#total").text(totals.toFixed(2)); 
} 

$(document).ready(function() { 
calculatePound(); 
}); 

上面的代码没有错误。但问题是,<'span id="total"'>是空的或值为0.0

我想要做的是计算每个磅的实际价格并显示它。
我怎样才能使它工作中使用此代码?或者我离我想要达到的目标太远了?
谢谢。

回答

3

不能使用val(),该方法主要用于获得形式元素,如输入,选择和textarea的值。您可以使用text()

function calculatePound() { 
    var totals= 0; 
    $(".price").each (function() { 
     totals= totals+ parseFloat("0" + $(this).text()); 
    }); 
    $("#total").text(totals.toFixed(2)); 
} 
+0

而且也许这将是明智的interduce OP的关键字'var' – andlrc

+0

哇!很酷的人非常感谢! :d – noob

+0

@NULL你是绝对正确的,我更新的代码。 –