如何添加从html表中获取的html内容? [英] How to add html contents taken from an html table?

查看:85
本文介绍了如何添加从html表中获取的html内容?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这个脚本

$('table#preview td.price').each(function(){
var price = parseInt($(this).html());
var total;
if(price == ''){
price = 0;
}
total += price;
alert(total);
});

它的作用是获取具有类价格的列,然后将其全部相加.

What it does is get the column that has the class price then supposedly adds it all up.

但是,我从这段代码中得到的仅仅是NaN.我不明白代码有什么问题.

However, all I get from this code is NaN. I don't get what's wrong with the code.

请注意脚本 if(price =='').我这样做是因为表中最初没有内容.

Please note the script if(price == ''). I've done this because initially there are no contents in the table.

此处是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>

推荐答案

尝试使用.text()方法而不是.html()方法,它有望帮助摆脱NaN错误.我想在每次迭代的范围之外声明total,这样就不会每次都被重置.尝试一下,我稍微简化了一下,还包括了对数字price的检查:

Try using the .text() method instead of .html() method, it should hopefully help get rid of the NaN errors. You'll want to declare the total outside the scope of each iteration so it doesn't get reset each time. Try giving this a go, I've simplified it slightly to also include a check against the number 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);

更新

这是 jsFiddle . N.B. .html()也应该起作用.

Update

Here's a jsFiddle. N.B. .html() should also work.

这篇关于如何添加从html表中获取的html内容?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆