我有这个脚本
$('table#preview td.price').each(function(){
var price = parseInt($(this).html());
var total;
if(price == ''){
price = 0;
}
total += price;
alert(total);
});
Run Code Online (Sandbox Code Playgroud)
它的作用是获得具有类价格的列,然后据说将其全部添加.
但是,我从这段代码得到的只是NaN.我不明白代码有什么问题.
请注意脚本if(price =='').我这样做是因为最初表中没有内容.
编辑:这里的HTML
<table>
<tr>
<th>Name</th>
<th>Price</th>
</tr>
<tr>
<td>pen</td>
<td class="price>6</td>
<td>paper</td>
<td class="price>8</td>
</tr>
</table>
Run Code Online (Sandbox Code Playgroud)
尝试使用该您需要.text()方法而不是.html()方法,它应该有助于摆脱NaN错误.total在每次迭代的范围内声明外部,以便每次都不会重置.试试这个,我稍微简化了一下,还包括对数字的检查price:
var total = 0;
$('table#preview td.price').each(function()
{
var price = parseInt($(this).text());
if (!isNaN(price))
{
total += price;
}
});
alert('The total is: ' + total);
Run Code Online (Sandbox Code Playgroud)
这是一个jsFiddle.NB .html()也应该工作.
| 归档时间: |
|
| 查看次数: |
1199 次 |
| 最近记录: |